简体   繁体   English

第一次在C中使用pthreads,为什么这些都不返回什么?

[英]First time using pthreads in C, why is nothing returned from these ones?

In the following code: 在下面的代码中:

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

I've been unable to get anything back other than zero for the finalScalarProduct, and both sp1 and sp2 are zero also. 对于finalScalarProduct,我一直无法获得零以外的任何值,并且sp1和sp2均为零。 I believe it's something to do with the NULL argument being passed in pthread_join. 我相信这与在pthread_join中传递的NULL参数有关。 I don't really understand what this argument is for. 我真的不明白这个说法是为了什么。

Any help appreciated! 任何帮助表示赞赏!

That's because pthread_create returns zero upon success . 这是因为pthread_create 成功时将返回零 The value is not the result of the main thread function, but the result of the thread creation (that might fail in some cases). 该值不是主线程函数的结果,而是线程创建的结果(在某些情况下可能会失败)。

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

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

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