I have a thread that puts data in a buffer and multiple threads that will read their portions of data from the buffer.
How can I create a synchronization mechanism to satisfy those requirements:
- Writer thread writes all data into buffer and lets all reader threads run at the same time (ok, i did it with Semaphore). Then waits for all of them to complete their turn. I could not use WaitForMultipleObjects since threads are not terminating but rather one round of loop is ending. Maybe an event for each reader thread and when loop ends they will signal it and Writer will use WaitForMultipleObjects to wait for all threads to finish their round of loop?
- Reader threads read their data, do their job for that round and somehow let Writer thread to put the next data. Please note that, Writer should start its next round of loop when all of the threads finish their turn.
How to implement such mechanism? as i said, only thing i can think of seems to be:
Writer:
for (;;)
{
PutDataIntoBuffer();
for (i = 0; i < threadCount; ++i)
{
ResetEvent(threadEvents[i]); //so that all events will be nonsignaled
}
ReleaseSemaphore(sem, threadCount, NULL);
WaitForMultipleObjects(threadCount, threadEvents, TRUE, INFINITE);
}
Readers:
for (;;)
{
WaitForSingleObject(sem, INFINITE);
DoWhateverToBeDoneWithData();
SetEvent(threadEvents[myThreadIndex]); //writer, wait for me too!
}
What are better ways of doing this?
You should use a Readers-writer lock.
In Windows there is a Slim Reader/Writer lock which I recommend that you have a look at.