Thread synchronization--Using a critical section

Source: Internet
Author: User
Tags thread

A critical section is an easy way to ensure that only one thread at a time can access data. Regardless of which thread occupies the critical section object, it can access the protected data, while the other threads must wait until the thread that occupies the critical section is released, so that the data in the critical section is not accessed by more than one thread at the same time.

In MFC, the Cctiticalsection class is used to create a critical section instance, such as:CCriticalSection CriticalSection;

When a thread is ready to access data in a critical area, its member function lock () must be called to lock (), such as: CriticalSecion.Lock(); if no thread occupies a critical section, lock () can provide access to the critical section data to the calling purebred, and then call the member function unlock () when the thread completes each data operation. For release, other threads can occupy the critical section. For example, CriticalSection.UnLock(); you can define a data instance:class CDataArray
{
private:
  int iArray[10];
  CCriticalSection CriticalSection;
public:
  CDataArray(){};
  ~CDataArray(){};
  void SetData(int iValue);
  void GetDataArray(int aArray[10]);
};

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.