Note that there are some explanatory texts on larger screens.

plurals
  1. POPOSIX semaphores/threads not working correctly?
    primarykey
    data
    text
    <p>I have the following code:</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;semaphore.h&gt; #include&lt;pthread.h&gt; sem_t semr; void* func(void* i) { sem_wait(&amp;semr); printf("\nInstance %d running",*(int*)i); //sem_post(&amp;semr); return NULL; } int main(void) { sem_init(&amp;semr,0,1); void* (*fp)(void*); int s1,s2,s3,val=0; pthread_t t1,t2,t3; fp=&amp;func; val=1; s1=pthread_create(&amp;t1,NULL,fp,(void*)&amp;val); val=2; s2=pthread_create(&amp;t2,NULL,fp,(void*)&amp;val); val=3; s3=pthread_create(&amp;t3,NULL,fp,(void*)&amp;val); pthread_join(t1,NULL); pthread_join(t2,NULL); pthread_join(t3,NULL); return 0; } </code></pre> <h2>This is my understanding of what happens:</h2> <p>The first thread(<code>t1</code>) executes successfully. The subsequent threads(<code>t2</code> and <code>t3</code>) though, are blocked, since I never <code>sem_post</code> the semaphore. The <code>pthread_join</code>s will make <code>main()</code> wait for all 3 threads to terminate.</p> <h2>This is what happens:</h2> <p>Neither thread will output <em>anything</em>. Not even <code>t1</code>s output(see question 1 below)</p> <h2>However,</h2> <p>removing all <code>pthread_join</code>s has a better effect in terms of what I expect: <code>t1</code> executes successfully and the command prompt is returned.</p> <p>My questions:</p> <ol> <li><p>According to the sample code on <a href="http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html" rel="nofollow">this page</a>, <code>main()</code> should wait for <code>t2</code> and <code>t3</code> to terminate (in addition to successfully executing <code>t1</code> <em>and</em> outputting <em>something</em>). Am I using <code>pthread_join</code> incorrectly here? What's happening?</p></li> <li><p>Why happens to the blocked threads(<code>t2</code> and <code>t3</code>)? Are the threads forced to terminate due to <code>main()</code> returning?</p></li> </ol>
    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