Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your initialization and use of the semaphores seems correct - they are a natural choice for producer-consumer queues - it's condvars that are not, (condvars have no count and so require while loops for correct operation even if your OS does not support the spurious wakeup feature).</p> <p>Your use of the buffer, however, seems a bit 'off'. I presume that the buffer is supposed to be circular? If so, you should be setting the index back to 0 whenever the front, or rear, index reaches the end of the array. You should be doing this inside the mutex lock in both the producer and consumer code. The check on the indexes should be solely to reset them to the start of the buffer and should not change the operation of the semaphore signal/wait in any way.</p> <p>That, and you seem to be joining the threads as soon as they are created. Usually, to test/demonstrate producer/consumer operation, threads are not continually created, immediately joined, (so that the constructing thread has to immediately wait), and then left to terminate. It's more common to run up some producer and consumer threads that loop, continually producing/consuming messages, (perhaps with a very short sleep loop - those kind of loops that some developers say have no valid use and are an anti-pattern).</p> <p>Continually creating/terminating/destroying threads is very wasteful and will result, in your test code, in an app that is performing nearly all overhead and very little producer/consumer.</p> <p>Last thing - don't join to threads without thinking about it for a second or two first. It may not be optimal, it may not be necessary, it may be a hindrance, it may be a disaster. If the join is solely to keep your main thread, (and so process), from terminating early, it may be better to find another way - wait on keyboard input or use a long-term sleep() loop.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload