(reprint) Pthreads thread (ii) thread synchronization--Mutex/Lock

Source: Internet
Author: User
Tags mutex

Pthreads thread (ii) thread synchronization--Mutex/Lock

  The Mutex (mutex) is the abbreviation for "Mutual exclusion". Mutexes are the primary way to implement thread synchronization and to protect simultaneous write-shared data.
Mutex protection for shared data is like a lock. In Pthreads, only one thread can lock the mutex at any time, so only one succeeds when multiple threads attempt to lock the mutex. No other thread can lock the mutex until the line threads unlocked the mutex is locked. The thread must be wheeled to access the protected data.
  A thread with mutex is often used to update global variables. Ensures that multiple threads update the same variables to run in a safe manner, with the result being the same as the results of a thread processing. This updated variable belongs to a "critical section" (critical).


The typical order for using mutexes is as follows:

    • Create and initialize a mutex
    • Multiple threads try to lock the mutex
    • Only one thread can successfully lock to change mutex
    • Lock successful threads to do some processing
    • Thread unlocks the mutex
    • Another thread gets a mutex, repeating the process
    • Finally destroy the mutex amount

  When multiple threads compete for the same mutex, the failed thread blocks at the lock call. You can replace "lock" with "Trylock", and it will not block if it fails. when protecting shared data, it is the programmer's responsibility to verify that the mutex is needed. For example, if four threads update the same data, but only one thread uses the mutex, the data may be corrupted.

To create and destroy mutex amounts:
Pthread_mutex_init (mutex,attr)  Pthread_mutex_destroy (mutex)  Pthread_mutexattr_init (attr)  

usage :

The mutex must be declared with the type pthread_mutex_t type and must be initialized before use, there are two ways to initialize the mutex:
Declared when statically, such as: pthread_mutex_t Mymutex = Pthread_mutex_initializer;
Using the Pthread_mutex_init () function dynamically, this method allows the Property object attr to set the mutex amount.
The mutex is unlocked after it is initialized.
The Attr object is used to set the properties of the mutex object, which must be declared as the pthread_mutext_attr_t type when used, and the default value can be null. The Pthreads standard defines three types of optional mutex attributes:

    • Protocol (PROTOCOL): Specifies that the protocol is used to prevent the priority change of the mutex
    • Upper Priority (prioceiling): Specifies the maximum priority of the mutex
    • Process Sharing (process-shared): Specifies the process share mutex

Note that all implementations provide these three first-of-a-possible mutex attributes.
The Pthread_mutexattr_init () and Pthread_mutexattr_destroy () functions are used to create and destroy mutex Property objects, respectively.
Pthread_mutex_destroy () should be used to release mutex objects that do not need to be reused.

Locking and unlocking mutexes:

function :

Pthread_mutex_lock (Mutex)  Pthread_mutex_trylock (mutex)  Pthread_mutex_unlock (mutex)  

usage :

The thread uses the Pthread_mutex_lock () function to lock the specified mutex variable, and if the mutex is already locked by another thread, the call will block the thread until the mutex is unlocked.
Pthread_mutex_trylock () would attempt to lock a mutex. However, if the mutex is already locked, the routine would return immediately with a "busy" error code. This routine is useful in pthread_mutex_trylock ().

Try to lock a mutex, however, if the mutex is locked, the program returns immediately and returns a busy error value. This function is useful for blocking deadlocks in the event of a priority change. threads can use Pthread_mutex_unlock () to unlock the amount of mutex they occupy. This function can be called when one thread completes the use of the protected data, while other threads are getting mutexes to work on the protected data. If there is a situation, an error will occur:

    • Mutex has been unlocked
    • Mutex is occupied by another thread

Mutexes are not so "magical", in fact, they are the "gentlemen's bargain" of participating threads. When writing code, be sure to lock correctly and unlock the mutex.
Q: There are multiple threads waiting for the same locked mutex, and when the mutex is unlocked, that thread will first lock the mutex?
A: Unless the thread uses a priority scheduling mechanism, the thread will be allocated by the system scheduler, and that thread will be the first to lock the mutex is random.

Case:

1 #include <stdlib.h>2 #include <stdio.h>3 #include <unistd.h>4 #include <pthread.h>56 typedefstructCt_sum7{8IntSum9 pthread_mutex_tLock;10}ct_sum;1112void * ADD1 (void *Cnt13{Pthread_mutex_lock (& ((ct_sum*) CNT)Lock));15Forint i=0; I <50; i++)16{(* (ct_sum*) CNT). Sum + =I18}Pthread_mutex_unlock (& ((ct_sum*) CNT)Lock));20Pthread_exit (NULL);21stReturn0;22}23void * ADD2 (void *Cnt24{Pthread_mutex_lock (& ((ct_sum*) CNT)Lock));26Forint i=50; i<101; i++)27{(* (ct_sum*) CNT). Sum + =I29}Pthread_mutex_unlock (& ((ct_sum*) CNT)Lock));31Pthread_exit (NULL);32Return0;33}3435int main (void)36{37pthread_t Ptid1, Ptid2;38Ct_sum CNT;Pthread_mutex_init (CNT &Lock), NULL);cnt.sum=0;41Pthread_create (&ptid1, NULL, ADD1, &CNT);Pthread_create (&ptid2, NULL, ADD2, &CNT);   pthread_join (ptid1,null);  Pthread_join (ptid2,null);  printf ("sum%d\n", cnt.sum);  Pthread_mutex_destroy (CNT & Lock));    0 return;                    * 

Original address: http://www.cnblogs.com/dongsheng/p/4186358.html

(reprint) Pthreads thread (ii) thread synchronization--Mutex/Lock

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.