1 , thread creation, termination, and control:
Any process starts with a main thread, and if it needs to be regenerated into a thread, use the pthread_create function, in which you can specify the properties of the thread, the thread routine, and the parameters passed to the thread routine. A thread routine is a user-defined function, and the code that the thread executes. When the thread routine returns, the thread ends up running, or it can display the call pthread_exit to exit. After the thread is created, the thread ID can be obtained with the pthread_self function. The function pthread_join causes the process to wait for the thread to terminate, and after the call Pthread_join the process is suspended until a specified thread (specified in the parameter thread of Pthread_join) terminates. The Pthread_detach function, on the other hand, makes it unnecessary for the process to wait for the end of the thread, allowing the process to continue to perform other operations, and the resources that are consumed by the detach thread are automatically retracted by the system after the execution ends.
2 , mutual exclusion between threads:
A mutually exclusive operation is to modify a piece of code or a variable only when one thread executes the code, and the other threads cannot enter the code at the same time or modify the variable at the same time. Pthread commonly used Pthread_mutex mutexes to implement thread mutex operations. The pthread_mutex_init function is used to initialize a mutex variable. The pthread_mutex_lock function is used to lock the mutex variable, and if the mutex has been locked by the thread locked, the thread that called the function is blocked until the mutex is unlocked. Pthread_mutex_trylock attempts to lock the mutex, but does not cause blocking when the mutex is locking, but returns quickly. The pthread_mutex_unlock function unlocks the mutex. The Pthread_mutex_destroy is used to release the resources that the mutex occupies.
3 , thread synchronization:
Synchronization is a number of threads waiting for an event to occur, and when that event occurs, it begins to continue executing. Use conditional variables for synchronization in Linux threads. The function pthread_cond_init is used to create a condition variable. pthread_cond_wait and pthread_cond_timewait are used to wait for the condition variable to be set, it is worth noting that these two wait calls need a locked mutex mutex, This is to prevent the competition from the possibility that other threads might set the condition variable before actually entering the wait state. pthread_cond_broadcast is used to set the condition variable, even if the event occurs and causes all threads waiting for the event to no longer block. The pthread_cond_signal is a blocking state that is used to dismiss a waiting thread. Pthread_cond_destroy The resource used to release a condition variable.
Thread execution process and thread functions