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:
accurate timeout is hard to achieve and
I want to process the data (write to disk) when
numof resources are all available (write larger size of data is faster). Therefore, for example, if less thannumof 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.
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 utilityFlex-Bufferand host it on Github. Hope it will help others with similar concerns.