繁体   English   中英

多线程输出混乱

[英]Multithreading Output Confusion

考虑以下主要部分

     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个零并不清楚! 任何猜想???

您的问题在这里:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM