Thread Communication (i)--Mutual exclusion lock

Source: Internet
Author: User
Tags mutex ticket

When using threads, it is often important to note that access-critical resources are locked.

Forgetting to add locks during the coding process due to carelessness will bring unpredictable errors. This kind of error is difficult to reproduce when a single run or small concurrency, when the data is large, the number of users increased, the system crashes, large data errors caused. Cause loss.

The mutex in a thread is similar to the semaphore of a process, and can also be seen as a PV operation to protect critical resources and ensure that only one thread accesses it.

The following code is a no-lock error code, which also involves some of the small details that you need to be aware of when threading programming is mentioned earlier.

1#include <pthread.h>2#include <unistd.h>3#include <iostream>4 5 using namespacestd;6 7 classThreadinterface8 {9  Public:Ten     voidCreateThread (void* (*func) (void*)); One     voidWaitthread (); A Private: - pthread_t M_ptread;  - }; the  - voidThreadinterface::createthread (void* (*func) (void*)) - { -Pthread_create (&m_ptread, NULL, func, NULL);  + } -  + voidThreadinterface::waitthread () A { at Pthread_join (M_ptread, NULL); - } -  - classMutexlockinterface - { -  Public: in     voidCreatemutexlock (); -     voidGetmutexlock (); to     voidReleasemutexlock (); +     voidDestroymutexlock (); - Private:   the pthread_mutex_t M_mutexlock;  * }; $ Panax Notoginseng voidMutexlockinterface::createmutexlock () - { the     intret = Pthread_mutex_init (&M_mutexlock, NULL); +     if(0!=ret) Acout<<"Init Mutex error!"; the } +  - voidMutexlockinterface::getmutexlock () $ { $Pthread_mutex_lock (&m_mutexlock); - } -  the voidMutexlockinterface::releasemutexlock () - {WuyiPthread_mutex_unlock (&m_mutexlock); the } -  Wu voidmutexlockinterface::D estroymutexlock () - { AboutPthread_mutex_destroy (&m_mutexlock); $ } -  -  - classService A { +  Public: the     Static void* Run (void*)//class member Thread function removes the this pointer for static -     { $         //M_mutexlock.getmutexlock (); the         if(0==m_tickets) the         { thecout<<"Stop operate!"<<Endl; the         } -         Else in         { thecout<<"Window2:we has"<<m_Tickets<<"Tickets"<<Endl; theSleep1); About--m_tickets; the         } the         //M_mutexlock.releasemutexlock (); the     } +     intSetData (intData) {M_tickets =data;}; -     intGetData () {returnm_tickets;}; the     Static intm_tickets;Bayi     Staticmutexlockinterface M_mutexlock; the }; the intService::m_tickets =1;//static variable out-of-class initialization - mutexlockinterface Service::m_mutexlock; -  the intMain () the { the Service Srv; the threadinterface Thread; - Srv.m_MutexLock.CreateMutexLock (); the      theThread.createthread (&srv.run); the 94     //Srv.m_MutexLock.GetMutexLock (); the     if(0==srv.getdata ()) the     { thecout<<"Stop operate!"<<Endl;98     } About     Else -     {101cout<<"Window1:we has"<<srv.getdata () <<"Tickets"<<Endl;102Sleep1);//delay 1s waiting thread 2103Srv.setdata (Srv.getdata ()-1);104     } the     //Srv.m_MutexLock.ReleaseMutexLock ();106Thread.waitthread ();//waiting for thread to end recycle107Cout<<srv.getdata () <<Endl;108     return 0;109}

The above code is a ticket for the scene, pawn ticket only one left, two windows at the same time people need to buy tickets.

The thread does not lock, and the result is as follows:

Obviously this is not the result we want, only one ticket sold out two, the last remaining tickets show 1!

Remove the comment line, the critical resource operation is lock, and then run the program, get the results consistent with the expected!

This is why the thread mutex exists.

Thread Communication (i)--Mutual exclusion 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.