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

标签 c multithreading pthreads

在下面的代码中:

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/

相关文章:

c - 分配结构堆与堆栈 : Pthread_create

在 C 中创建线程

我可以在多线程(pthreads)应用程序中捕获 SIGSEGV 和其他信号并打印导致它的线程或所有线程的回溯吗?

c - 每次在我的 Linux 机器上创建新套接字时如何运行代码?

c - 通过引用将变量传递给另一个函数时变量的值发生变化

c - 如何初始化动态分配结构的成员

java - 两次启动另一个 Activity 时,线程不更新 textview

C# 从多个线程对表执行批量更新,不会出现死锁

c - 为 pthread_cond_broadcast 调用同步线程

c++ - 注入(inject)的 DLL 主循环导致进程崩溃