我是多线程编程的新手,我有一个关于“pthread_create”行为的问题
这是代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#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 < 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<NTHREADS; i++) {
    tids[i] = i;
    pthread_create(&threads[i], NULL/*&attr*/, do_work, (void *) &tids[i]);
   }

  /* Wait for all threads to complete then print global sum */
/*
  for (i=0; i<NTHREADS; i++) {
    pthread_join(threads[i], NULL);
  }*/
  printf ("Done. Sum= %e \n", sum);

  sum=0.0;
  for (i=0;i<ARRAYSIZE;i++){
  a[i] = i*1.0;
  sum = sum + a[i]; }
  printf("Check Sum= %e\n",sum);

}

执行的结果是:
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

所有线程都被创建,执行不是顺序的(remove pthread_join),但是函数do_work是按顺序执行的,并且依赖于线程。这意味着迭代0到99999由线程0完成,迭代100000到199999由线程1完成等等。。。
问题是为什么0到99999的迭代不是由线程2完成的?

最佳答案

这是因为迭代范围是根据以下行中从0到N的线程数计算的:

start = (*mytid * ITERATIONS);

在循环中创建并传递该数字:
for (i=0; i<NTHREADS; i++) {
    tids[i] = i;
    ...

换言之,当N为非负时,2+N永远不会为0来执行从0到99999的迭代。

09-30 23:33