Hayri Uğur Koltuk
Hayri Uğur Koltuk

Reputation: 3020

How to create a one-to-many wait mechanism in WinAPI

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:

  1. 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?
  2. 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?

Upvotes: 3

Views: 288

Answers (2)

Ajay
Ajay

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

M&#229;rten Wikstr&#246;m
M&#229;rten Wikstr&#246;m

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

Related Questions