1. Mutex mutex
Synchronization: access to resources in an orderly manner. Mutual exclusion: only one is executing at any time; but for multi-threaded programs, the problem of access conflicts is very common. The solution is to introduce a mutex (Mutex, MutualExclusive Lock), and obtain the lock. The thread can complete the "read-modify-write" operation and then release the lock to other threads. Threads that have not obtained the lock can only wait but cannot access the shared data. In this way, the three-step operation of "read-modify-write" forms an atomic operation. Either execute them all or neither, they will not be interrupted in the middle of execution, and this operation will not be done in parallel on other processors.
Mutex locks are represented by variables of type pthread_mutex_t. Initialized with pthread_mutex_init and destroyed with hread_destroy(). Returns 0 on success and an error number on failure. . If the Mutex variable is statically allocated (global variable or static variable), it can also be initialized with the macro definition PTHREAD_MUTEX_INITIALIZER, which is equivalent to initializing with pthread_mutex_init and the attr parameter is NULL
A thread can call pthread_mutex_lock to obtain the Mutex. If at this time another thread If the thread has called pthread_mutex_lock to obtain the Mutex, the current thread needs to wait until another thread calls pthread_mutex_unlock to release the Mutex, and the current thread is awakened before it can obtain the Mutex and continue execution. This means that if a thread locks the mutex but does not unlock it, and another thread wants to obtain the mutex, it must hang up and wait until the locked thread unlocks the mutex and releases the mutex, and then the thread is awakened and can obtain the mutex.
If a thread wants to obtain the lock but does not want to hang and wait, it can call pthread_mutex_trylock. If the Mutex has been acquired by another thread, this function will fail and return EBUSY without causing the thread to hang and wait.
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<pthread.h> 4 static int g_count=0; 5 void * addWrite(void * arg) 6 { 7 int count=0; 8 int value=0; 9 while(count++ <5000) 10 { 11 value=g_count; 12 printf("g_count is %d\n",g_count); 13 g_count=value+1; 14 } 15 } 16 int main() 17 { 18 pthread_t id1; 19 pthread_t id2; 20 int ret=pthread_create(&id1,NULL,addWrite,NULL); 21 int res=pthread_create(&id2,NULL,addWrite,NULL); 22 pthread_join(id1,NULL); 23 pthread_join(id2,NULL);
We create two threads, each increasing g_count 5000 times. Under normal circumstances, the final counter should be equal to 10000, but in fact the result is different every time the program is run. Sometimes the count reaches more than 5000. Sometimes the count reaches more than 6,000, but after adding the lock (on) the fifth line, add pthread_mutex_init, as shown below
Result:
After adding the lock, 10000 is output.
2. Implementation principle of lock and unlock
In order to realize the mutex lock operation, most architectures provide the swap or exchange instruction. The instruction is The function is to exchange data between the register and the memory unit. Since there is only one instruction, atomicity is guaranteed. Even on a multi-processor platform, the bus cycles for accessing memory are sequential. The exchange instruction on one processor is executed on another processor. The swap instruction can only wait for bus cycles. This is shown in the pseudocode below. The lock release operation in unlock is also implemented with only one instruction to ensure its atomicity.
3. Deadlock
・Generally, if the same thread calls lock twice, during the second call, because the lock has already been occupied, The thread will hang up and wait for other threads to release the lock. However, the lock is occupied by itself. The thread is suspended without a chance to release the lock, so it will be in a suspended waiting state forever. This is called deadlock. ). Another typical deadlock situation is this: Thread A acquires lock 1, and thread B acquires lock 2. At this time, thread A calls lock to try to acquire lock 2. As a result, it needs to hang and wait for thread B to release lock 2, and this At this time, thread B also called lock to try to obtain lock 1. As a result, it needed to wait for thread A to release lock 1, so both threads A and B were in a suspended state forever.
Conditions for deadlock formation
①. Mutual exclusion condition: A resource can only be used by one thread at a time.
②. Request and retention conditions: When a process is blocked due to requesting resources, it will retain the obtained resources.
③. Non-deprivation conditions: The resources that have been obtained by the process cannot be forcibly deprived before they are used up.
④Cyclic waiting conditions: A head-to-tail cyclic waiting resource relationship is formed between several processes.
If more threads and more locks are involved, it is more likely to cause Deadlock problem. When writing a program, you should try to avoid acquiring multiple locks at the same time. If it is necessary to do so, there is a principle: if all threads need multiple locks, they must follow the same order (the most common is the address order of the Mutex variable) If the lock is obtained, deadlock will not occur. For example, if lock 1, lock 2, and lock 3 are used in a program, and the addresses of their corresponding Mutex variables are lock 1
The above is the content of Linux-thread synchronization and mutual exclusion. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!