Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Copied from an <a href="https://stackoverflow.com/questions/4258283/waiting-win32-threads/4258377#4258377">answer</a> to <a href="https://stackoverflow.com/questions/4258283/waiting-win32-threads/">one of my earlier questions</a>. My question concerns Win32 threads but the described consept pretty much the same with pthreads.</p> <ol> <li>Use a semaphore in your queue to indicate whether there are elements ready to be processed.</li> <li>Every time you add an item, call <code>sem_post()</code> to increment the count associated with the semaphore</li> <li>In the loop in your thread process, call <code>sem_wait()</code> on the handle of your semaphore object</li> </ol> <p>Here is a tutorial for <a href="http://www.csc.villanova.edu/~mdamian/threads/posixsem.html" rel="nofollow noreferrer">POSIX Semaphores</a></p> <p>But first like the other guy said, you have to make Q thread-safe.</p> <pre><code>void *func(void *newWorker) { struct workerType* worker = (struct workerType*) newWorker; while(numServed &lt; maxJobs) { //if(!Q.empty()) { // No need to ask if Q is empty. // If a thread passes the sem_wait function // there has to be at least one job in the Q sem_wait(&amp;semaphore); pthread_mutex_lock(&amp;mutex); struct jobType* job = Q.front(); numServed++; cout &lt;&lt; job-&gt;jobNum &lt;&lt; " was served by " &lt;&lt; worker-&gt;workerNum &lt;&lt; endl; Q.pop(); pthread_mutex_unlock(&amp;mutex); //sleep(worker-&gt;runTime); No need to sleep also //} } } void *job(void *jobdata) { struct jobType *job = (struct jobType*) jobdata; //sleep(job-&gt;arrivtime); pthread_mutex_lock(&amp;mutex); Q.push(job); pthread_mutex_unlock(&amp;mutex); sem_post(&amp;semaphore); // Inform the workers that another job is pushed. } </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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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