Easy Thread Safe Resource Synchronization in MFC

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Environment: VC6 SP5 Win9x, WinNT 4.0, Win2000

When a program is using more then one thread, there will be in most cases the need of synchronizing the data. This can be ‘easily’ done by using one of the provided synchronization classes of MFC: CMutex, CSemaphore, CEvent, CCriticalSection. In some of the simple cases these classes are everything one needs to implement the desired syncronisation between all treads.

To obtain access to a locked resource you have to use a CSingleLock or CMultiLock object. These objects have a simple interface. Either you are granted access to the data or you don’t. But sometimes we need a more complex locking mechanism and then we are left in the blue. I needed a mechanisme that could be called something like this : ‘Single-Write, Multiple-Read, Write-Has-Priority-To-Read’.

Single-Write means that only one thread is granted access in order to edit the protected data. When a request to write or read the data comes, the requesting thread is blocked.

Multiple-read means that multiple threads are granted access to read the
data at the same time. A request to edit the data will blocked, requests to read
will be granted access.

>Write-Has-Priority-To-Read means that when a request to edit the data is done, while the data is locked, the calling thread waits until the reading thread(s) are finnished. When there are new requests to read the data after the ‘write-request’ is done the threads are blocked until the writing-operation is finneshed, eventhough the write-thread is still waiting until he is granted access to the data.

To create this behaviour I create my own locking object. This encloses a CMutex and two CEvents. The CMutex is used to control the internal data. The two events are used to signal a write-thread or some read-thread that the access to the data is granted. This object is has alsoo a simple interface to control the data:

READING:

  • void StartReading();
  • void StopReading();


Sample code:

 lock.StartReading (); 

// we have access now
lock.StopReading ();

WRITING:


  • BOOL StartWriting();
  • void StopWriting();

When two threads launch a request for edit the data only one thread may be granted access. The request of the other thread is denied. The ‘StartWriting’ function returns whether the request is accepted or not. Usign a loop it is possible to allow multiple threads requesting a write-operation.

Sample code:



while (!lock.StartWriting) Sleep (100); // wait a little while
// we have access now …
lock.StopWriting ();

Downloads

Download source – 2 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read