在下面的代码中:
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/