gpt4 book ai didi

c - 第一次在 C 中使用 pthreads,为什么这些线程没有返回任何内容?

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:13 24 4
gpt4 key购买 nike

在下面的代码中:

int main (int argc, const char * argv[]) {
// insert code here...

pthread_t t1, t2;
int sp1, sp2;

sp1 = pthread_create( &t1, NULL, getScalarProduct, NULL);
sp2 = pthread_create( &t2, NULL, getScalarProduct, NULL);
pthread_join( t1, NULL);
pthread_join( t2, NULL);

printf("Seperate scalars: %d %d\n", sp1, sp2);
finalScalarProd = sp1 + sp2;


printf("Result: %d\n", finalScalarProd);

return 0;
}

除了 finalScalarProduct 的零以外,我无法取回任何其他值,而且 sp1 和 sp2 也为零。我相信这与在 pthread_join 中传递的 NULL 参数有关。我真的不明白这个论点是为了什么。

感谢任何帮助!

最佳答案

那是因为 pthread_create returns zero upon success .该值不是主线程函数的结果,而是线程创建的结果(在某些情况下可能会失败)。

void * threadMainFunc(void * arg) {
// modify arg like this
int * ip = (int *)arg;
*ip = 3; // this is the "return value"
return NULL;
}

pthread_create( &t1, NULL, threadMainFunc, &sp1);

关于c - 第一次在 C 中使用 pthreads,为什么这些线程没有返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9655104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com