2

While trying to figure out how to implement a Producer/Consumer Queue in Qt, I stumpled upon several SO answers, blogs and sites linking to this site:

You're doing it wrong...

I got the point of this site, but people are usually referring to the code example which is in the referenced blog:

Threading without the headache

The blog has a small code example attached, the core of it being posted by KornP in this SO answer:

Qt moveToThread() vs calling new thread when do we use each

So if you take a closer look we have the following behaviour:

  1. Producer P produces an item, while Consumer C waits for events to appear in its event loop.
  2. P forwards the produced data through a signal and returns to event loop idling.
  3. C receives the signal in its event loop and consumes the data.
  4. C emits a signal to the producer thread and returns to event loop idling.
  5. Start over from 1.

In other words: while P is producing, C does nothing and while C is producing, P does nothing.

What is the point of having a producer and consumer like this in two different threads?
Wouldn't a single thread accomplish exactly the same?

1 Answer 1

4

in this simple case, yes, there's no real benefit in using threads other than showing how threads work I guess. It's still interesting though: P's event loop keeps on running while the actual work is done by C. This is what you want in order to keep the user interface (which P might very well be) responsive.

Things get more interesting with concrete examples. Suppose C comsumes data by storing it in a buffer, and dumps it to a file when the buffer has enough data. This dumping might take while, but P can just continue it's business putting data in the queue without noticing C is busy nor without any slowdown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.