c++webserver/Chapter III Linux Thread Development

1. Threads

1. Definition

  1. Similar to a process, threads are a mechanism that allows applications to perform multiple tasks concurrently. ** A process can contain multiple threads. ** All threads in the same program execute the same program independently and share the same global memory area, including initialized, uninitialized, and heap memory segments. (Traditionally, a UNIX process is only a special case of a multithreaded program that contains only one thread)
  2. Processes are the smallest unit of CPU allocation, and threads are the smallest unit of operating system scheduling.
  3. Threads are lightweight processes (LWP: Light weight Process), and threads are still processes in Linux.
  4. View the LwP number of the specified process: ps-Lf PID

2. Threads (meaningful)

  1. Information between processes is difficult to share. Since parent-child processes do not share memory except for read-only code snippets, some methods of interprocess communication are necessary for information exchange between processes.
  2. Calling fork() to create a process is relatively expensive, and even with write-time replication, there is still a hot need to replicate a variety of process properties, such as memory page tables and file descriptor tables, which means that fork() calls still cost a lot of time.
  3. Threads can share information easily and quickly. Simply copy the data into shared (global or heap) variables.
  4. Threads are typically created 10 times faster or more than processes. There is a shared virtual address space between threads, and there is no need to copy memory using write-time replication or page tables.

3. Shared and non-shared

  1. Stack sum. text is blocked, multiple threads
  2. Signal mask: blocking signal set, pending signal set, etc.

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-mJI2BY3E-1645463459665) (Chapter III Linux Thread Development.assets/image-20220221220702357.png)]

4. Thread Functions

!!! Note that additional compiled libraries are required at compile time - lpthread

1. Create a thread

Typically, the main function is the main thread, and the rest is called the sub-thread. Subthreads do not share main thread code. Subthreads are just function content

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
	1.	Outgoing parameter, thread ID after successful thread creation.
	2.	Set thread properties, typically using the default (NULL)
	3.	Function pointer, the logical code that the subthread needs to process (code executed by the thread)
	4.	Parameters given to a function
	Return value: success returns 0, failure returns error number, different from errno;
		  Signal to get error number: char *strerror(int errnum);[string.h]

void * callback(void *arg){... return null;}
2. Terminate Threads

Terminates a thread and terminates which thread is called from which thread;

If the main thread exits, the child thread exits as well

void pthread_exit(void *retval);
	1.	You need to pass a pointer as a return value to pthread_ Obtained in join (); NULL if not needed;
		!!Note that you cannot return a local variable!!.
3. Get the thread ID of the current thread
pthread_t pthread_self(void);
	Returns an ID, long integer (ld);
4. Compare two threads with the same number

Different operating systems, pthread_ The implementations of type T are different, either unsigned long integers or structured ones. So you have to use a function

int pthread_equal(pthread_t t1, pthread_t t2);
5. Connect with a terminated child thread / Recycle child thread resources

Blocking threads, calling once to block until one child thread is recycled, and only one child thread can be recycled,

int pthread_join(pthread_t thread, void **retval);
	1.	ID of the child thread that needs to be recycled
	2.	Accept the return value when the child thread exits (the outgoing parameter is the value that exit exits or returns)
	Return value: success 0, failure return non-0 (error number);
6. Separation

Separate a thread and let it run on its own. At the end you will be released.

  1. Threads cannot be categorized multiple times, resulting in unexpected behavior
  2. Cannot connect to a detached thread, error will occur (will not crash)
int pthread_detach(pthread_t thread);
	1.	id of the thread that needs to be detached
	Return value: 0 for success and -1 for failure;
7. Thread Cancellation

Cancel the thread and let it terminate (task termination);

Cancellation depends on the state and type of the thread that was set when the thread was created.

Not a legislative termination, threading can only be cancelled when execution reaches the cancellation point (system-specified, presumably user-to-kernel switching)

int pthread_cancel(pthread_t thread);
	1.	id of the thread that needs to be cancelled
	Return value: success 0, failure return non-0 (error number);

5. Thread Properties

1. Initialize thread state
pthread_attr_t attr; //State Structures
int pthread_attr_init(pthread_attr_t *attr);
2. Release resources for thread properties
int pthread_attr_destroy(pthread_attr_t *attr);
3. Get the state property of thread detachment

Set to pthread_create was created with

int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
	1.	Attribute variable
	2.	Status: [PTHREAD_CREATE_DETACHED (detached) | PTHREAD_CREATE_JOINABLE (default, not detached)]
4. Set the state property of thread detachment
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);

Video link: https://www.nowcoder.com/study/live/504 (Free, I look and feel that the teacher is speaking very well!)

Keywords: C++ Linux Unix

Added by sheila on Mon, 21 Feb 2022 19:22:04 +0200