Mikhail  Zimka
Mikhail Zimka

Reputation: 714

Multithreading: several producers + one consumer

I've got the following problem
I have several threads (producers) calculating positions of moving objects and one thread (consumer) that prints calculation results. Every thread has it's own time scale. The problem of synchronization is that consumer can print results only when all of the producers calculate position at the printing moment. In other words consumer have to compare it's current time with the same of the producers and to decide whether the results can be printed or not. I found a similar example where synchronization was made with a semaphore, but there was only one producer there. Does anyone know a smart solution?

Upvotes: 0

Views: 98

Answers (1)

Amadan
Amadan

Reputation: 198324

Consumer loop:

  • wait n times
  • collect data
  • do its thing
  • signal all n producers

Producer loop (n in parallel):

  • do its thing
  • make data available
  • signal to consumer
  • wait

(Sorry, don't know anything about QT, so just the general algorithm)

EDIT: If the producers have a buffer rather than wait to synchronise, then you can do this:

Consumer loop:

  • wait, then check all buffers; repeat while any buffer is empty
  • collect data; if any buffer was full, signal to that producer
  • do its thing

Producer loop (n in parallel):

  • do its thing
  • wait if buffer is full
  • queue data
  • signal to consumer

Upvotes: 0

Related Questions