First, what is a thread
Multiple lines of execution in a program are called threads. A more accurate definition is that a thread is a control sequence within a process. All processes have at least one thread. When a process executes a fork call, it creates a new copy of the process, which has its own variable and its own PID, and its schedule is independent, and its execution is almost entirely independent of the parent process. When a new thread is created in the process, the new execution thread will have its own stack (and hence its own local variable), but share global variables, file descriptors, signal processing functions, and current directory state with its creator.
An application mixed with input, compute, and output can be executed by separating the parts into 3 threads, improving the performance of the program execution. When the input or output thread waits for a connection, another thread can continue to execute. So if a process can only do one thing at any one time, the thread can make it do something else that is useful while waiting for things like connectivity. In general, switching between threads requires that the operating system does more work than switching between processes, so multiple threads need less resources than many processes.
Threads also have some drawbacks: ① in multithreaded programs, the likelihood of errors caused by subtle deviations in timing or accidental sharing of variables is significant. ② Debugging multithreaded threads is much more difficult than debugging a single-threaded thread, because the interaction between them is very difficult to control. A program that ③ a large number of calculations into two parts and runs the two parts as two different threads does not necessarily run faster on a single-processor machine, unless the calculation does allow the different parts of it to be computed simultaneously, and the machine that runs it has multiple processor cores to support true multi-processing.
Second, the first thread of the threaded
Let's start by looking at a new function pthread_create for managing threads, which is to create a new process, similar to the fork function that creates a new process, which is defined as follows:
#include <pthread.h>intvoid * (*start_routine) (voidvoid *arg);
The first parameter is a pointer to the pthread_t type data, and when the thread is created, the variable that the pointer points to is written to an identifier, which we use to refer to the new thread. The next parameter is used to set the properties of the thread. We don't normally need special attributes, so we just set this parameter to NULL. The last two parameters tell the thread to start the executing function and the arguments passed to the function, respectively.
void * (*start_routine) (void *)
The above line tells us that we must pass a function address, a pointer to void that is a parameter, and a pointer to void. Therefore, you can pass a parameter of either type and return a pointer of any type. When called with Fork, the parent-child process continues in the same position, but the return value of the fork call is different, but for the new thread, we must explicitly provide it with a function pointer, and the new process will begin executing at this new location.
The thread terminates execution by calling the Pthread_exit function as if the process had called the Exit function at the end. The purpose of this function is to terminate the thread that invokes it and return a pointer to an object. Note that it must never be used to return a pointer to a local variable, because after the thread calls the function, the local variable no longer exists, which causes a serious program vulnerability. The function is defined as follows:
#include <pthread.h>void pthread_exit (void *retval);
The role of the Pthread_join function in the thread is equivalent to the wait function that is used to collect the child process information in the process, defined as follows:
#include <pthread.h>int pthread_join (pthread_t th,void **thread_return);
The first parameter specifies the thread that will be waiting, and the thread is specified by the identifier returned by Pthread_create. The second argument is a pointer to another pointer, which points to the return value of the thread.
#include <stdio.h>#include<unistd.h>#include<stdlib.h>#include<string.h>#include<pthread.h>void*thread_function (void*Arg);CharMessage[] ="Hello World";intMain () {intRes; pthread_t A_thread; void*Thread_result; Res= Pthread_create (&a_thread, NULL, Thread_function, (void*) message); if(Res! =0) {perror ("Thread creation failed"); Exit (Exit_failure); } printf ("waiting for thread to finish...\n"); Res= Pthread_join (A_thread, &Thread_result); if(Res! =0) {perror ("Thread Join failed"); Exit (Exit_failure); } printf ("Thread joined, it returned%s\n", (Char*) thread_result); printf ("Message is now%s\n", message); Exit (exit_success);}void*thread_function (void*Arg) {printf ("Thread_function is running. Argument was%s\n", (Char*) arg); Sleep (3); strcpy (Message,"bye!"); Pthread_exit ("Thank for the CPU time");}
The results of the Gcc-o pthread1 Pthread1.c-lpthread run with GCC compiled under Linux are:
[email protected]:~/linux_c_driver/demo$./ for is now bye!
Three, synchronization
1, the signal volume synchronization
There are two sets of interface functions for the semaphore. A set of real-time extensions taken from POSIX for threading, and another group called System V semaphores, often used for process synchronization. The semaphore is a special type of variable that can be increased or decreased, but the key access to it is guaranteed to be an atomic operation. This means that if there are two (or more) threads in a program trying to change the value of a semaphore, the system will guarantee that all operations will proceed sequentially.
The semaphore function's name starts with Sem_, and the basic semaphore used in the thread is 4. The semaphore is created by the Sem_init function, which is defined as follows:
#include <semaphore.h>int sem_init (sem_t *sem,intint value);
This function initializes the semaphore object pointed to by the SEM, sets its sharing options, and gives it an initial integer value. The pshared parameter controls the type of semaphore and, if its value is 0, indicates that the semaphore is the local semaphore of the current process, otherwise the semaphore can be shared among multiple processes.
#include <semaphore.h>int sem_wait (sem_t *sem); int sem_post (sem_t *sem);
Both functions take a pointer to an object that is the semaphore initialized by the Sem_init call.
The role of the Sem_post function is to add 1 to the value of the semaphore in an atomic operation, which means that if two threads attempt to give a semaphore plus 1 at the same time, they do not interfere with each other, unlike if two programs can cause conflicts when reading, adding, and writing to the same file at the same time.
The sem_wait function subtracts 1 of the semaphore's value by atomic operation, but it waits until the semaphore has a non-0 value to begin the subtraction operation. Therefore, if you call sem_wait on a semaphore with a value of 2, the thread will continue to execute, but the semaphore value will be reduced to 1. If Sem_wait is called on a semaphore with a value of 0, the function waits until another thread increases the value of the semaphore so that it is no longer 0.
The last semaphore function is Sem_destroy, the function of which is to clean up the semaphore after it is used, and it is defined as follows:
#include <semaphore.h>int Sem_destroy (sem_t *sem);
The example program pthread3.c is as follows:
#include <stdio.h>#include<unistd.h>#include<stdlib.h>#include<string.h>#include<pthread.h>#include<semaphore.h>void*thread_function (void*arg); sem_t Bin_sem;#defineWork_size 1024CharWork_area[work_size];intMain () {intRes; pthread_t A_thread; void*Thread_result; Res= Sem_init (&bin_sem,0,0); if(Res! =0) {perror ("Semaphore initialization failed"); Exit (Exit_failure); } Res= Pthread_create (&a_thread, NULL, thread_function, NULL); if(Res! =0) {perror ("Thread creation failed"); Exit (Exit_failure); } printf ("Input some text. Enter ' End ' to finish\n"); while(STRNCMP ("End", Work_area,3) !=0) {fgets (Work_area, Work_size, stdin); Sem_post (&Bin_sem); } printf ("\nwaiting for thread to finish...\n"); Res= Pthread_join (A_thread, &Thread_result); if(Res! =0) {perror ("Thread Join failed"); Exit (Exit_failure); } printf ("Thread joined\n"); Sem_destroy (&Bin_sem); Exit (exit_success);}void*thread_function (void*Arg) {sem_wait (&Bin_sem); while(STRNCMP ("End", Work_area,3) !=0) {printf ("You input%d characters\n", strlen (Work_area)-1); Sem_wait (&Bin_sem); } pthread_exit (NULL);}
The GCC compilation executes as follows:
[email protected]:~/linux_c_driver/demo$./'end'6 6 5 for thread to finish ... Thread joined
In the main thread, we wait until there is text input, and then call Sem_post to increase the semaphore value, which immediately returns the other thread from the sem_wait wait and begins execution. After counting the number of characters, it calls Sem_wait again and is blocked again until the main thread calls Sem_post again to increase the value of the semaphore. And this can easily lead to some errors, we modify the above program, the main function of the Read data loop modified to:
printf"Input some text. Enter ' End ' to finish\n"); while(STRNCMP ("End", Work_area,3) !=0) { if(STRNCMP (Work_area,"FAST",4) ==0) {Sem_post (&Bin_sem); strcpy (Work_area,"wheeee ..."); } Else{fgets (Work_area, Work_size, stdin); } sem_post (&Bin_sem); }
Now, if you enter fast, the program calls Sem_post to get the character count thread to run and to update the Work_area array with other data immediately. The program runs as follows:
[email protected]:~/linux_c_driver/demo$./'end'7 5 8 8 8for threadto finish ... Thread joined
The problem is that our program relies on it to receive text input for long enough so that another thread has time to count the number of characters in the workspace before it is ready for more words to be counted in the main thread. When we try to give it two sets of different words in a row quickly to statistics (keyboard input fast and the program automatically provides wheeee ... ), the second thread has no time to execute. But the semaphore has been increased more than once, so the character count thread will repeatedly count the number of characters and reduce the semaphore value until it becomes 0 again.
2, with mutual exclusion amount of synchronization
Another synchronous access method used in multithreaded programs is to use mutexes. It allows the programmer to lock an object so that only one thread can access it at a time. To control access to the critical code, you must lock a mutex before entering the code, and then unlock it after the operation is complete. The functions for the basic functions and semaphores for mutexes are very similar, and they are defined as follows:
#include <pthread.h>int pthread_mutex_init (pthread_mutex_t *mutex,const PTHREAD_MUTEXATTR_ T *murexattr); int pthread_mutex_lock (pthread_mutex_t *mutex); int pthread_mutex_unlock (pthread_mutex_t *mutex); int Pthread_mutex_destroy (pthread_mutex_t *mutex);
Similar to semaphores, the parameters of these functions are pointers to a previously declared object. For mutexes, this object is of type pthread_mutex_t. The attribute parameter in the Pthread_mutex_init function allows us to set the property of the mutex, and the property controls the behavior of the mutex. The property type defaults to fast, but it has a small drawback: if the program tries to call Pthread_mutex_lock on a mutex that has already been locked, the program will be blocked and the mutex will never be unlocked because the thread that owns the mutex is the thread that is now blocked. The program enters a deadlock state as well. This problem can be solved by changing the properties of the mutex, we can let it check the situation and return an error, or let it recursive operation, add multiple locks to the same thread, but must be careful to perform the same number of unlocking operations later.
Four, cancel a thread
Sometimes, we want a thread to be able to ask for the other one to terminate, just like sending a signal to it, the thread has a way to do this, and as with signal processing, the thread can change its behavior when it is requested to terminate.
#include <pthread.h>int pthread_cancel (pthread_t thread);
This function provides a thread identifier, and we can send a request to cancel it, but at the end of the cancellation request, things are a little more complicated. The thread can set its own cancellation state with Pthread_setcancelstate.
#include <pthread.h>int pthread_setcancelstate (int State,int *oldstate);
The value of the first parameter can be pthread_cancel_enable, which allows the thread to receive a cancellation request, or pthread_cancel_disable, which is the function of ignoring the cancellation request. The oldstate pointer is used to get the previous cancellation state. If the cancellation request is accepted, the thread can go to the second control level and set the cancellation type with Pthread_setcanceltype.
#include <pthread.h>int pthread_setcanceltype (int type,int *oldtype);
The type parameter can have two values: one is pthread_cancel_asynchronous, it will take action immediately after accepting the cancellation request, and the other is pthread_cancel_deferred, which will make it possible to accept the cancellation request Wait until the thread executes one of the following functions before taking action. Specifically, functions Pthread_join, pthread_cond_wait, pthread_cond_timewait, Pthread_testcancel, sem_wait, or sigwait.
The Oldtype parameter can hold the previous state, and if you do not want to know the previous state, you can pass NULL to it. By default, the cancellation state of a thread at startup is pthread_cancel_enable, and the cancellation type is pthread_cancel_deferred.
POSIX Threading Learning