Thread synchronization--Mutex amount

Source: Internet
Author: User

The concept of synchronization

Multiple threads can share memory space, and in a program it is inevitable that multiple threads should collaborate to complete a function. Then these threads may use a common resource. such as global variables, a file, and so on. In order to not create a conflict, a conflict can occur between write operations on multiple threads, while read operations are safe. This requires synchronization between multiple threads.

Principle of mutual exclusion amount

The mechanism of mutual exclusion to achieve synchronization is well understood. You can think of the mutex as a lock. Permissions on shared resources are only available when a thread obtains the lock. It can be understood that the thread has a lock on the shared resource and other threads do not have permission to operate. After this thread operation is complete, it needs to be unlocked so that other threads can obtain the lock. As you can imagine, the code structure that uses mutexes should be in this form:

/**/Get_mutex (); /* */... /*  */Release_mutex ();

Value, note that for shared resources that you want to protect, all threads should use the above code form, not just one or two threads using mutexes. Otherwise, a conflict will occur.

interface functions

A mutex variable is pthread_mutex_t represented by a data type. Must be initialized before it is used. There are both static and dynamic modes of initialization. The static way to set it to constant PTHREAD_MUTEX_INITIALIZER dynamic mode requires the use of the following two functions:

#include <pthread.h>int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);int pthread_mutex_destory(pthread_mutx_t *mutex);                    两个函数返回值:若成功,返回0;否则,返回错误编号

Where attr the parameter can be set to NULL means that the default initial mutex is used.

To lock the mutex, call pthread_mutex_lock if the mutex is locked, the calling thread will block knowing that the mutex is unlocked. Unlocking the mutex requires calling thepthread_mutex_unlock

#include <pthread.h>int pthread_mutex_lock(pthread_mutex_t *mutex);int pthread_mutex_unlock(pthread_mutex_t *mutex);                    两个函数返回值:若成功,返回0;否则,返回错误编
Instance

The mutex content is so much, write an example to practice:

#include <pthread.h>#include<stdio.h>int Global=0;p thread_mutex_t Mutex=Pthread_mutex_initializer;void*FUN1 (void*Arg) {    inti =0;  for(; I < -; i++) {Pthread_mutex_lock (&mutex); Global+=1; printf ("Thread 1 Write \t%d\n",Global); Pthread_mutex_unlock (&mutex); } pthread_exit ((void*)1);}void*fun2 (void*Arg) {    inti =0;  for(; I < -; i++) {Pthread_mutex_lock (&mutex); Global+=1; printf ("Thread 2 Write \t%d\n",Global); Pthread_mutex_unlock (&mutex); } pthread_exit ((void*)2);}intMain () {pthread_t tid1, Tid2; if(Pthread_create (&AMP;TID1, NULL, FUN1, NULL)! =0)        return-1; if(Pthread_create (&tid2, NULL, FUN2, NULL)! =0)        return-1; Sleep (5); return 0;}

Dead lock

One problem that can easily be caused by using mutexes is deadlock. Imagine, now a total of two mutex variable mutex1 mutex2 pthread1 occupy mutex1 want to request mutex2 , pthread2 possession mutex2 want to request mutex1 then these two threads will always block down, because no thread is willing to first release the possessive mutex. One way to avoid deadlocks is to lock all threads in the same order, and to strictly control the order in which the mutex is locked. This method is insufficient in the case of a lot of mutex and complex data structure. Another way is to send the spirit of selfless devotion, the thread first non-blocking pthread_mutex_trylock function to try to lock. If the function returns successfully, then the mutex can be used. If the function is returned incorrectly, it is recommended that the thread first unlock the original mutex. Keep trying for a while. However, this method has the meaning of guessing, based on the probability, the procedure is not efficient.

Thread synchronization--Mutex amount

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.