Linux thread synchronization mutex-Linux general technology-Linux programming and kernel information. The following is a detailed description. Compile g ++-o thread_mutex mutex. cpp-lpthread
Run./thread_mutex
If no mutex is added, the order of output AAAAAAAA and BBBBBBBBBB is chaotic.
If the mutex is added, 10 AAAA and 10 bbbbbbbbbb are output first.
CODE: # include
# Include
Using namespace std;
Pthread_mutex_t MyMutex;
Void * ThreadFuncA (void * p)
{
Pthread_mutex_lock (& MyMutex); // lock mutex
For (int j = 0; j <10; ++ j)
{
Cout <"AAAAAAAAAA" <
Sleep (1); // to see the difference between mutex and non-mutex
}
Pthread_mutex_unlock (& MyMutex); // release mutex
Return NULL;
}
Void * ThreadFuncB (void * p)
{
Pthread_mutex_lock (& MyMutex );
For (int j = 0; j <10; ++ j)
{
Cout <"bbbbbbbbbbbbb" <
Sleep (3); // to see the difference between mutex and non-mutex
}
Pthread_mutex_unlock (& MyMutex );
Return NULL;
}
Int main ()
{
Pthread_t MythreadID1; // thread ID
Pthread_t MythreadID2; // thread ID
Int ThreadRet1; // the return value of the thread.
Int ThreadRet2; // the return value of the thread.
// Initialize mutex
Pthread_mutex_init (& MyMutex, NULL );
// The return value can be used to determine whether the thread is successful.
ThreadRet1 = pthread_create (& MythreadID1, NULL, & ThreadFuncA, NULL );
ThreadRet2 = pthread_create (& MythreadID2, NULL, & ThreadFuncB, NULL );
Pthread_join (MythreadID1, NULL); // wait until the thread ends.
Pthread_join (MythreadID2, NULL); // wait until the thread ends.
Pthread_mutex_destroy (& MyMutex); // destroy mutex
} |