Note that there are some explanatory texts on larger screens.

plurals
  1. POpthread scheduling problems
    primarykey
    data
    text
    <p>I have two threads in a producer-consumer pattern. Code works, but then the consumer thread will get starved, and then the producer thread will get starved.</p> <p>When working, program outputs:</p> <pre><code>Send Data...semValue = 1 Recv Data...semValue = 0 Send Data...semValue = 1 Recv Data...semValue = 0 Send Data...semValue = 1 Recv Data...semValue = 0 </code></pre> <p>Then something changes and threads get starved, program outputs:</p> <pre><code>Send Data...semValue = 1 Send Data...semValue = 2 Send Data...semValue = 3 ... Send Data...semValue = 256 Send Data...semValue = 257 Send Data...semValue = 258 Recv Data...semValue = 257 Recv Data...semValue = 256 Recv Data...semValue = 255 ... Recv Data...semValue = 0 Send Data...semValue = 1 Recv Data...semValue = 0 Send Data...semValue = 1 Recv Data...semValue = 0 </code></pre> <p>I know threads are scheduled by the OS, and can run at different rates and in random order. My question: When I do a YieldThread(calls <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_yield.3.html" rel="nofollow noreferrer">pthread_yield</a>), shouldn’t the Talker give Listener a chance to run? Why am I getting this bizarre scheduling?</p> <p>Snippet of Code below. Thread class and Semaphore class are abstractions classes. I went ahead as stripped out the queue for data passing between the threads so I could eliminate that variable.</p> <pre><code>const int LOOP_FOREVER = 1; class Listener : public Thread { public: Listener(Semaphore* dataReadySemaphorePtr) : Thread("Listener"), dataReadySemaphorePtr(dataReadySemaphorePtr) { //Intentionally left blank. } private: void ThreadTask(void) { while(LOOP_FOREVER) { this-&gt;dataReadySemaphorePtr-&gt;Wait(); printf("Recv Data..."); YieldThread(); } } Semaphore* dataReadySemaphorePtr; }; class Talker : public Thread { public: Talker(Semaphore* dataReadySemaphorePtr) : Thread("Talker"), dataReadySemaphorePtr(dataReadySemaphorePtr) { //Intentionally left blank } private: void ThreadTask(void) { while(LOOP_FOREVER) { printf("Send Data..."); this-&gt;dataReadySemaphorePtr-&gt;Post(); YieldThread(); } } Semaphore* dataReadySemaphorePtr; }; int main() { Semaphore dataReadySemaphore(0); Listener listener(&amp;dataReadySemaphore); Talker talker(&amp;dataReadySemaphore); listener.StartThread(); talker.StartThread(); while (LOOP_FOREVER); //Wait here so threads can run } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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