Note that there are some explanatory texts on larger screens.

plurals
  1. POPosix threads problem
    text
    copied!<p>I am trying to understand pthreads by example. I have made the following code that is giving different answers everytime I run! Could anyone explain the bug please? TIA, Sviiya</p> <p>The code is here:</p> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define NUM_THREADS 4 struct thread_data { int thread_id; int sum; }; struct thread_data thread_data_array[NUM_THREADS]; void *PrintHello(void *threadarg) { struct thread_data *my_data; int taskid; int sum; my_data = (struct thread_data *) threadarg; taskid = my_data-&gt;thread_id; sum = my_data-&gt;sum; printf("Hello World! It's me, thread #%d\n", taskid); return my_data; } int main () { pthread_t threads[NUM_THREADS]; int rc; long t; int sum=0; for (t=0; t &lt; NUM_THREADS; t++) { printf("Hi! %ld\n", t); threads[t] = t; thread_data_array[t].thread_id = t; thread_data_array[t].sum = sum; rc = pthread_create(&amp;threads[t], NULL, PrintHello, (void *) &amp;thread_data_array[t]); } return 0; } </code></pre> <p>The output is here:</p> <pre><code>[user@office tmp]$ ./a.out Hi! 0 Hi! 1 Hello World! It's me, thread #0 Hello World! It's me, thread #1 Hi! 2 Hi! 3 Hello World! It's me, thread #2 [user@office tmp]$ ./a.out Hi! 0 Hi! 1 Hello World! It's me, thread #0 Hello World! It's me, thread #1 Hi! 2 Hi! 3 Hello World! It's me, thread #2 Hello World! It's me, thread #3 [user@office tmp]$ ./a.out Hi! 0 Hello World! It's me, thread #0 Hi! 1 Hello World! It's me, thread #1 Hi! 2 Hello World! It's me, thread #2 Hi! 3 Hello World! It's me, thread #3 [user@office tmp]$ ./a.out Hi! 0 Hi! 1 Hello World! It's me, thread #0 Hi! 2 Hi! 3 Hello World! It's me, thread #3 [user@office tmp]$ </code></pre>
 

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