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();
};