Reputation: 3020
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:
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?
Upvotes: 3
Views: 288
Reputation: 18411
If you are using VC10, you better use Concurrency::unbounded_buffer class which will handle everything for you. Just use Concurrency::send
, Concurrency::asend
to append message to it; Concurrency::receive
, Concurrency::try_receive
to read message from it. This class implements FIFO. There can be multiple readers as well as multiple writers.
Upvotes: 1
Reputation: 11344
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.
Upvotes: 3