多线程输出混淆

时间:2013-10-02 17:08:23

标签: c multithreading

考虑主要

中的以下部分
     tcount = 0;
     for (i=0; i<2; i++) {
      count[i] = 0;
      if (pthread_create(&tid[i], NULL, randint, (void *)&i) != 0) {
           exit(1);
      } else {
           printf("Created Thread %d\n", i);
      }
//        XXXXXXX
     }

     for (i=0; i<nthreads; i++) {
      printf("Waiting for thread %d to terminate\n", i);
      pthread_join(tid[i], NULL);
     }

和randint代码是:

void *randint(void *pint)
{
     int j, k;
     int rseed;

     j = *((int *)pint);
     printf("Started thread %d\n", j);
     while (tcount++ < NMAX) {
      count[j] += 1;
     }
     return(NULL);
}

输出为:

Created Thread 0
Created Thread 1
Waiting for thread 0 to terminate
Started thread 0
Started thread 0
Waiting for thread 1 to terminate

我很困惑为什么在输出中有:

Started thread 0
Started thread 0

我理解是否:

Started thread 0
Started thread 1

或者:

Started thread 1
Started thread 1

但是2个零点不清楚! 任何猜测???

1 个答案:

答案 0 :(得分:2)

你的问题在这里:

if (pthread_create(&tid[i], NULL, randint, (void *)&i) != 0) {

当您传入其值时,这会传递i地址。通常我们只是将整数作为void *传递给黑客。

if (pthread_create(&tid[i], NULL, randint, (void *)i) != 0) {
...
// in the thread we cast the void * back to an int (HACK)
j = (int)pnt;

i重置为0的原因是您在下一个循环中重新使用i

for (i=0; i<nthreads; i++) {
  printf("Waiting for thread %d to terminate\n", i);
  pthread_join(tid[i], NULL);
}

但即使您在此循环中使用了j,也不会获得Started thread 0然后1,因为在线程启动时,i的值可能已经改变,因为pthread_create(...)需要相对较长的时间。如果你在第二个循环中使用j,你可能会得到:

Started thread 1
Started thread 1

通过i传递给线程是正确的做法。如果它需要是一个地址,那么你应该为它的副本分配空间:

int *pnt = malloc(sizeof(i));
*pnt = i;
if (pthread_create(&tid[i], NULL, randint, (void *)pnt) != 0)
...
// remember to free it inside of the thread