Multithreading
A process can only do one thing at a time, while multiple threads can execute at the same time, and each thread handles its own independent task. Multithreading has many benefits:
- Simplifying code for handling asynchronous events
- Implement sharing of memory and file descriptors
- Improve the throughput of your program
- Improved response time
Mutual exclusion Lock
mutexes: Mutual-exclusion locks enable synchronization between threads through a lock mechanism, usually allowing only one key part of the code at the same time
When multiple threads control the same memory, the time gap for read and write operations can cause the data to be out of sync, and it is clear that this is the case:
For threads A, b at this time the same block of memory operation, but because the operation is almost simultaneous, it is assumed that when thread a reads data I, when the data I self-added 1 thread B is the original memory of the data I read out, and then thread A will be added to the data in memory, and thread B to read the I plus 1, Finally writes it to the memory, this program originally wants to carry on the two thread to the variable I carries on the two times the self-addition operation the final expected result should be 7, finally obtains the unusual result. For this critical variable operation, it is possible to cause unexpected results, and the mutex and condition variables are present to ensure that the data is only manipulated by one thread.
The result of the following program is also very good description of multi-threaded operation of the same variable instability:
#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <errno.h>intA =0;//used as the global variable to be changedpthread_mutex_t Mutex;//Mutual exclusion lock variablevoidThread1 (void*arg) {//pthread_mutex_lock (&mutex);//Locking printf("Thread1 a =%d\n", a); a++;//pthread_mutex_unlock (&mutex);}voidThread2 (void*arg) {//pthread_mutex_lock (&mutex); printf("Thread2 a =%d\n", a); a++;//pthread_mutex_unlock (&mutex);}voidThread3 (void*arg) {//pthread_mutex_lock (&mutex); printf("Thread3 a =%d\n", a); a++;//pthread_mutex_unlock (&mutex);}intMainvoid) {pthread_t tid1, Tid2, TID3;//For receiving thread ID intErr//Error code void* Tret;//return value //Create three threadsPthread_create (&tid1, NULL, (void*) Thread1, NULL); Pthread_create (&tid2, NULL, (void*) thread2, NULL); Pthread_create (&TID3, NULL, (void*) Thread3, NULL);//wait for the secondary thread to endErr = Pthread_join (TID1, &tret);if(Err! =0) {perror ("Join"); } err = Pthread_join (Tid2, &tret);if(Err! =0) {perror ("Join"); } err = Pthread_join (TID3, &tret);if(Err! =0) {perror ("Join"); }printf("Result A:%d\n", a);//View the final results Exit(0);}
The results of multiple executions are as follows:
Found several times the execution result is not the same, originally the program is three threads to the same global variable 3 times plus 1 operation result should be 0, three-way, because the data between the threads is not synchronized, resulting in this result.
We will now get this result when we cancel the comments in each of the thread functions in the program:
This shows the mutual exclusion lock to ensure the synchronization of data between threads.
The use of mutexes should be noted:
- Must be initialized before use
- Locking, if the lock variable is locked, the thread that is currently trying to lock is blocked until the mutex is freed by another thread
- The thread that calls the unlock function must be a thread that locks the mutex
- Deadlocks can occur when a thread tries to lock the mutex in the opposite order of another thread
- If a thread tries to lock a mutex two times, it itself will be locked into a deadlock state
Deadlock: Refers to two or more than two processes in the course of execution, because of competing resources or due to the communication between each other caused by a blocking phenomenon, if there is no external force, they will not be able to proceed. At this point the system is in a deadlock state or the system produces a deadlock, and these processes, which are always waiting for each other, are called deadlock processes
condition Variable
Conditional variables: a mechanism for synchronizing with global variables shared between threads
use condition variables to be aware of:
- To initialize before using
- The condition variable is usually evaluated under the protection of the mutex, and if the conditional expression is false, the thread is blocked based on the condition variable.
- After a thread is blocked by a condition variable, it can be activated by pthread_cond_signal and Pthread_cond_broadcast, and pthread_cond_signal activates a waiting thread in the queued order, Pthread_cond_ Broadcast activates all waiting threads.
- When a condition variable is no longer in use, it needs to be cleared, clearing the function: Pthread_cond_destory, the condition variable can be cleared only if no thread waits for the condition variable, otherwise the ebusy is returned.
- You must have a loads lock on the line before calling pthread_cond_wait () to prevent multiple threads from requesting pthread_cond_wait () at the same time.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Multi-thread mutex, condition variable