Thread synchronization--using mutexes

Source: Internet
Author: User
Tags mutex thread

The mutual exclusion is very similar to the critical region and is far more complex than the critical region. Because mutual exclusion not only enables the secure sharing of resources within different threads of the same application, but also enables secure sharing of resources between threads of different applications. Through CMutex to complete the coprime between threads, namely: CMutex Mutext;

So we can define data objects like this:

#include "afxmt.h"
class CDataArray
{
private:
  int iArray[10];
  CMutex Mutex;
public:
  CDataArray(){};
  ~CDataArray(){};
  void SetData(int iValue);
  void GetDataArray(int aArray[10]);
};

The member functions are implemented as follows:

void CDataArray::SetData(int iValue)
{
  CSingleLock SingleLock(&Mutex);
  SingleLock.Lock();
  for (int i=0;i<10;i++)
    iArray[i]=iValue;
}
void CDataArray::GetDataArray(int aArray[10])
{
  CSingleLock SingleLock(&Mutex);
  SingleLock.Lock();
  for (int i=0;i<10;i++)
    aArray[i]=iArray[i];
}

In order to access a mutex, it is important to establish a CSingleLock or CMultiLock object for access control. If the mutex is not consumed by the thread, the current calling thread can become a mutex occupier. To achieve access to mutexes, you invoke the CSingleLock member function lock (), which is:

Singlelock.lock ();

If a thread occupies a mutex, the system suspends the current calling thread until the mutex is freed, at which point the suspended thread wakes up and gets control of the mutex.

The release of the mutex is achieved by invoking the CSingleLock member function unlock (). Cdataarray member functions are automatically unlocked when they exit. Because CSingleLock is created on the vertebral stack, the system automatically completes the call to unlock ().

This article is that I am in the learning multitasking multithreading process notes, for everyone to refer to, hope to get you advice.

This article supporting source code

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.