Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Do you want your main thread to do anything in particular after all the threads have completed?</p> <p>If not, you can have your main thread simply call <code>pthread_exit()</code> instead of returning (or calling <code>exit()</code>). </p> <p>If <code>main()</code> returns it implicitly calls (or behaves as if it called) <code>exit()</code>, which will terminate the process. However, if <code>main()</code> calls <code>pthread_exit()</code> instead of returning, that implicit call to <code>exit()</code> doesn't occur and the process won't immediately end - it'll end when all threads have terminated.</p> <ul> <li><a href="http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_exit.html" rel="noreferrer">http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_exit.html</a></li> </ul> <p>Can't get too much quick-n-dirtier.</p> <p>Here's a small example program that will let you see the difference. Pass <code>-DUSE_PTHREAD_EXIT</code> to the compiler to see the process wait for all threads to finish. Compile without that macro defined to see the process stop threads in their tracks. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;pthread.h&gt; #include &lt;time.h&gt; static void sleep(int ms) { struct timespec waittime; waittime.tv_sec = (ms / 1000); ms = ms % 1000; waittime.tv_nsec = ms * 1000 * 1000; nanosleep( &amp;waittime, NULL); } void* threadfunc( void* c) { int id = (int) c; int i = 0; for (i = 0 ; i &lt; 12; ++i) { printf( "thread %d, iteration %d\n", id, i); sleep(10); } return 0; } int main() { int i = 4; for (; i; --i) { pthread_t* tcb = malloc( sizeof(*tcb)); pthread_create( tcb, NULL, threadfunc, (void*) i); } sleep(40); #ifdef USE_PTHREAD_EXIT pthread_exit(0); #endif return 0; } </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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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