0

考虑以下主要部分

     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个零不清楚!!!有猜吗???

4

1 回答 1

2

你的问题在这里:

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

这是传入您应该传入其值的地址i通常,我们只是将整数作为 avoid *作为 hack 传递。

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
于 2013-10-02T17:44:57.073 回答