How to lock a semaphore with multiple count

185 Views Asked by At

Semaphore is a counting object. The question is how to lock it with multiple count?

For example, I would like to call lock(num, timeout) function. It locks when there are at least num resources available, or fails when timeout passes, but there are still resources less than num .

Is it possible on Windows? Or maybe using pthread?

Currently on Windows, WaitForSingleObject decreases the count of object by 1. I think calling WaitForSingleObject multiple times cannot solve the problem because:

  1. accurate timeout is hard to achieve and

  2. I want to process the data (write to disk) when num of resources are all available (write larger size of data is faster). Therefore, for example, if less than num of resources are separately locked, I then may have to release (just after I lock) them for next time because the rests are still not available even timeout passes. I think it is a poor design. Need helps.

1

There are 1 best solutions below

0
guan boshen On

After searching online, I think there is no simple and offical way to implement a semaphore with multiple locks. System V supports this kind of semaphore, but I think it is awkward to use it on Windows.

Instead, I choice to use condition-signal machanism (based on pthreads) as mentioned by @MayurK with one producer (that acquires the data) and one consumer (that stores the data to disk). To make things easier, I implement a buffer handle utility Flex-Buffer and host it on Github. Hope it will help others with similar concerns.