Linux thread synchronization mutex

Source: Internet
Author: User
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
}

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.