Thread synchronization--using semaphores

Source: Internet
Author: User
Tags count resource semaphore thread

In addition to the use of critical sections and mutexes to complete synchronization between threads, you can also use Semaphore CSemaphore. Another benefit of using semaphores is that signals allow multiple threads to use shared resources at the same time, which is similar to the PV operation in the operating system. It indicates the maximum number of threads accessing the shared resource at the same time.

There is a counter inside the semaphore that when a thread accesses a shared resource, the counter automatically decrements, and when it is 0 o'clock, it no longer allows other threads to access the shared resource until one of the threads frees the shared resource to complete the protection of the shared resource.

You must provide an initialization value and a maximum count value when creating a semaphore, such as:

CSemaphore Semaphore (2,2);

You can dynamically create a CSemaphore object in the constructor of a class, such as:

Semaphore=new CSemaphore (2,2);

Once the semaphore CSemaphore is established, it can be prepared to use it to count the access to the shared resources. To complete the count process, you should first create a csinglelock or CMultiLock object, such as:

CSingleLock Singlelock (semaphore);

To reduce the count of this signal semaphore, simply call the member function lock () of the CSingleLock object:

Singlelock.lock ();

Similarly, by calling unlock () to release the semaphore, that is:

Singlelock.unlock ();

So that we can declare the class:

#include "afxmt.h"
class CSharedResource
{
private:
  CSemaphore* ptrSemaphore;
public:
  CSharedResource();
  ~CSharedResource();
 
  void AccessResource();
};

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.