c - 我的 pthread 函数出错

标签 c pthreads

我有一个程序,它应该从用户 = (n) 处获取一个数字,并创建一个线程来计算从 1 到 n 的总和。我知道 ((n+1)*n)/2 会给我相同的结果。当我运行程序时,会创建一个线程,但是当我询问'TotalSum'的值时,给出的是0,而不是根据用户输入进行计算,为什么?

# include <stdio.h>
# include <pthread.h>

void * thread_calc(void *);
int TotalSum=0;

int main()
{
    int iNumber,iCount;
    pthread_t tid, tid2;
    printf("Enter Number Up to Which You want to Sum :");
    scanf("%d",&iNumber);    
    pthread_create(&tid,NULL,thread_calc,(void *) iNumber);
    //pthread_create(&tid2,NULL,thread_calc,(void *)(iNumber+);




    printf("Thread %d running, Final Sum is : %d \n", tid,TotalSum);
    //printf("Thread %d running, Final Sum is : %d \n", tid2,TotalSum);
    //    return 0;
}

void *thread_calc(void *num)
{
    int *iNumber;
    iNumber=(int*)num;

    TotalSum = ((*iNumber + 1)* (*iNumber))/2;

    pthread_exit(NULL);    
}

我的输出:(例如,用户输入 10)

Enter Number Up to Which You want to Sum :10
Thread 536937120 running, Final Sum is : 0

最佳答案

您的主线程没有等待线程完成,并且您没有将正确的参数传递给线程函数:

  pthread_create(&tid, NULL,thread_calc, &iNumber); //pass the address of iNumber
  pthread_join(tid, NULL); // main thread waits for the thread_calc to return

当主线程退出时,整个进程就会死亡。因此,您需要等待线程返回 pthread_join() 。 您将 iNumber 本身作为指针值传递给线程函数。但线程函数实际上期望它的参数是 一个指针(当您在 thread_calc() 中取消引用 iNumber 时)。

关于c - 我的 pthread 函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068222/

相关文章:

c - 使用 doxygen 记录配置宏

c - 在 C 中实现数组绑定(bind)金丝雀

c - 开关盒 : error: case label does not reduce to an integer constant

c - pthread_cond_wait(&cond_t, &mutex);解锁然后锁定互斥锁?

c - 阅读是否涉及多线程应用程序中的任何锁定?

c - strtok:获取分隔符之前的值,而不仅仅是之后的值

c++ - 将 C 变量传递给 C++ 函数

c - 使用信号量交换两个 fork 进程

C 线程程序

c - 多线程应用程序中的错误处理