Example of "Linux" mutex mutex thread synchronization

Source: Internet
Author: User
Tags mutex usleep

0, Mutual exclusion amount

Mutex under Windows

is a kernel object that checks whether the current thread ID and the thread ID that owns the mutex are consistent each time WaitForSingleObject and ReleaseMutex.

When multiple wait** is required to correspond to multiple ReleaseMutex, when ReleaseMutex too many times if you find that the current possessive mutex thread ID and the current call ReleaseMutex the thread ID is inconsistent, only return flase, GetLastError returns Error_not_owner with no other side effects.

When the thread that owns the mutex exits before release, the mutex is "abandoned" and the mutex is automatically reclaimed by the system for other threads to request.

Allow multiple Waits

WaitForSingleObject (Hmutex, time);

WaitForSingleObject (Hmutex, itme);

Multiple waits for multiple releases

ReleaseMutex (Hmutex);

ReleaseMutex (Hmutex);

Mutex under Linux

You can set whether a property of a mutex can be locked multiple times by the same thread, and you can set the scope of that mutex, that is, for synchronization between processes or between different threads of the same process.

The relevant API will be described in the Code comments section.

1. Related API

//initialize a mutex with attribute (can is NULL) intPthread_mutex_init ( pthread_mutex_t*Mutex,Constpthread_mutexattr_t*mutexattr); //locka mutex intPthread_mutex_lock (pthread_mutex_t*mutex);                                                                                                        Ulock a mutex intPthread_mutex_unlock (pthread_mutex_t*mutex);                                                                                                       Destroy a mutex intPthread_mutex_destroy (pthread_mutex_t*mutex); intpthread_mutexattr_setpshared ( pthread_mutexattr_t*MattR,intPshared//Pthread_process_share | Pthread_process_private      ); intpthread_mutexattr_getshared (PTH read_mutexattr_t*MattR,int*pshared); intPthread_mutexattr_settype ( pthread_mutexattr_t*attr,intType//PTHREAD_MUTEX_TIMED_NP--Default value //pthread_mutex_recurisive_np-Allow a thread lock Multitimes //pthread_mutex_errorcheck_no--Check error lock, return EDEADLK if the same thread want to lock //Pthread_mutex_adaptive_no--ADAPTIVE lock, the simplest lock) intPthread_mutexattr_gettype ( pthread_mutexattr_t*attr,int*type) 

2. Demo

#include <iostream>#include<pthread.h>#include<unistd.h>#include<errno.h>using namespacestd;/** * Initialize a mutex with attribute (can be NULL) * int Pthread_mutex_ini T (* pthread_mutex_t* Mutex, * const pthread_mutexattr_t* MUTEXATTR); * Lock a mutex * int pthread_mutex_lock (pthread_mutex_t* mutex); * * Unlock a mutex * int pthread_mutex_unlock (pthread_mutex_t* mutex); * * Destroy a mutex * int Pthread_mutex_destroy (pthread_mutex_t* mutex); * * int pthread_mutexattr_setpshared (* pthread_mutexattr_t* mattr, * int pshared//pthread_process_share | P Thread_process_private *); * * int pthread_mutexattr_getshared (* pthread_mutexattr_t* mattr, * int* pshared); * * int pthread_mutexattr_settype (* pthread_mutexattr_t* attr, * int type//pthread_mutex_timed_np--de Fault value *//PTHREAD_MUTEX_RECURISIVE_NP--Allow a thread lock Multitimes *//PTHR       Ead_mutex_errorcheck_no--Check error lock, return EDEADLK if the same thread want to lock *            Pthread_mutex_adaptive_no--ADAPTIVE lock, the simplest lock *) * * * int Pthread_mutexattr_gettype (* pthread_mutexattr_t* attr, * int* type *) * *********************************************/void* Work_thread (void*p) {    if(NULL = =p)returnconst_cast<Char*> ("Invalid thread argument"); pthread_mutex_t* Pmutex = (pthread_mutex_t*) (p); //Current thread IDpthread_t Nthreadid =pthread_self (); inti =0;  while(+ + i <=3)    {        //Lock Multi TimesPthread_mutex_lock (Pmutex);                Pthread_mutex_lock (Pmutex); cout<<"Thread"<< Nthreadid <<"is running!"<<Endl; //And so unlock multi TimesPthread_mutex_unlock (Pmutex);        Pthread_mutex_unlock (Pmutex); Usleep ( +*1);//1 miliseconds    }            returnconst_cast<Char*> ("------Finish-----------");}void* WORK_THREAD2 (void*p) {    if(NULL = =p)returnconst_cast<Char*> ("Invalid thread argument"); pthread_mutex_t* Pmutex = (pthread_mutex_t*) (p); //Current thread IDpthread_t Nthreadid =pthread_self (); inti =0;  while(+ + i <=3)    {        //if current thread can not enter a mutex,//and the function Pthread_mutex_trylock would RETURN immediatly        if(Ebusy = =Pthread_mutex_trylock (Pmutex)) cout<<"Other thread is lock the resouce, I am waiting."<<Endl; Else{cout<<"Thread"<< Nthreadid <<"is running!"<<Endl;            Pthread_mutex_unlock (Pmutex); Usleep ( +*1);//1 miliseconds        }    }            returnconst_cast<Char*> ("------Finish-----------");}intMain () {Constsize_t Nthreadcount =3;    pthread_t Threadids[nthreadcount]; intNret =-1;    pthread_mutex_t Mutex;    pthread_mutexattr_t mutexattr; void* PRet = NULL;//Thread return value//Allow a thread lock multi TimesNret = Pthread_mutexattr_settype (&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP); Nret= Pthread_mutex_init (&mutex, &mutexattr); if(0!=nret)return-1;  for(size_t i =0; I < Nthreadcount-1; ++i) {nret= Pthread_create (&threadids[i], NULL, Work_thread, (void*) (&mutex)); if(0!=nret)Continue; } nret= Pthread_create (&threadids[nthreadcount-1], NULL, Work_thread2, (void*) (&mutex)); if(0!=nret) Cerr<< Endl <<"Work_thread2 created falied!"<<Endl;  for(size_t i =0; i < Nthreadcount; ++i) {nret= Pthread_join (Threadids[i], &PRet); if(0==nret) {cout<<"Thread"<< Threadids[i] <<"finished!"                 "It ' s return value is"<< (Char*) PRet <<Endl; }} Pthread_mutex_destroy (&mutex); return 0;}

3. Implementation results

Example of "Linux" mutex mutex thread synchronization

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.