gpt4 book ai didi

c - 多线程输出困惑

转载 作者:太空宇宙 更新时间:2023-11-04 08:52:29 25 4
gpt4 key购买 nike

主要考虑以下部分

     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);
}

随机代码是:

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 * 作为 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

关于c - 多线程输出困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19142712/

25 4 0
文章推荐: c - 尝试释放()链表节点会导致 C 中的段错误
文章推荐: python - 如何删除django中的用户?
文章推荐: python - Django - 如何查询与 "listing"对象关联的所有用户
文章推荐: html - 使
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com