Note that there are some explanatory texts on larger screens.

plurals
  1. POtest "pthread_create" function behaviour
    primarykey
    data
    text
    <p>I am new in multi-threaded programming and I have a question about "pthread_create" behaviour this is the code : </p> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define NTHREADS 10 #define ARRAYSIZE 1000000 #define ITERATIONS ARRAYSIZE / NTHREADS double sum=0.0, a[ARRAYSIZE]; pthread_mutex_t sum_mutex; void *do_work(void *tid) { int i, k=0,start, *mytid, end; double mysum=0.0; mytid = (int *) tid; start = (*mytid * ITERATIONS); end = start + ITERATIONS; printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1); for (i=start; i &lt; end ; i++) { a[i] = i * 1.0; mysum = mysum + a[i]; } sum = sum + mysum; } int main(int argc, char *argv[]) { int i, start, tids[NTHREADS]; pthread_t threads[NTHREADS]; pthread_attr_t attr; for (i=0; i&lt;NTHREADS; i++) { tids[i] = i; pthread_create(&amp;threads[i], NULL/*&amp;attr*/, do_work, (void *) &amp;tids[i]); } /* Wait for all threads to complete then print global sum */ /* for (i=0; i&lt;NTHREADS; i++) { pthread_join(threads[i], NULL); }*/ printf ("Done. Sum= %e \n", sum); sum=0.0; for (i=0;i&lt;ARRAYSIZE;i++){ a[i] = i*1.0; sum = sum + a[i]; } printf("Check Sum= %e\n",sum); } </code></pre> <p>the result of execution is : </p> <pre><code>Thread 1 doing iterations 100000 to 199999 Done. Sum= 0.000000e+00 Thread 0 doing iterations 0 to 99999 Thread 2 doing iterations 200000 to 299999 Thread 3 doing iterations 300000 to 399999 Thread 8 doing iterations 800000 to 899999 Thread 4 doing iterations 400000 to 499999 Thread 5 doing iterations 500000 to 599999 Thread 9 doing iterations 900000 to 999999 Thread 7 doing iterations 700000 to 799999 Thread 6 doing iterations 600000 to 699999 Check Sum= 8.299952e+11 </code></pre> <p>all thread are created and the execution is not sequential (remove pthread_join), but the function do_work is executed in order and depend on thread. it means iterations 0 to 99999 are done by thread 0 and iterations 100000 to 199999 are done by thread 1 etc ...</p> <p>the question is here why for example iterations 0 to 99999 is not done by thread 2 ? </p>
    singulars
    1. This table or related slice is empty.
    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