c - 我想创建更多线程来计算用户给定输入的总和

标签 c pthreads

我有一个程序,要求用户输入一个数字来计算 1 到 n 的总和(n 是用户输入的数字),使用线程。我试图弄清楚如何让第二个线程计算 1 到 n+1,第三个线程计算 1 到 n+2,依此类推。

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

void * thread_sum(void *);
int TotalSum=0;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;

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_sum,(void *)&iNumber);
    pthread_create(&tid2,NULL,thread_sum,(void *)&iNumber);
    for(iCount=1;iCount<=iNumber;iCount=iCount+2)
    {
        pthread_mutex_lock(&mVar);
        TotalSum=TotalSum + iCount;
        pthread_mutex_unlock(&mVar);
    }

    pthread_join(tid,NULL);

    printf("Thread %d running, Final Sum is : %d \n", tid,TotalSum);

}
void *thread_sum(void *no)
{
    int *iNumber,iCount, res;
    iNumber=(int*)no;

    for(iCount=2;iCount<=*iNumber;iCount=iCount+2)
    {
        pthread_mutex_lock(&mVar);
        TotalSum=TotalSum + iCount;
        pthread_mutex_unlock(&mVar);
    }
    pthread_exit(NULL);    
}

最佳答案

您可以发送要计算的元素数量,而不是使用 iNumber 的地址调用 thread_sum。

pthread_create(&tid,NULL,thread_sum,(void *)(iNumber+1));
pthread_create(&tid2,NULL,thread_sum,(void *)(iNumber+2));

然后在thread_sum中使用它:

void *thread_sum(void *no)
{
    int *iNumber,iCount, res;
    iNumber=(int)no;

    for(iCount=2;iCount<=iNumber;iCount=iCount+2)

希望有帮助

关于c - 我想创建更多线程来计算用户给定输入的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067346/

相关文章:

c - 维度矩阵中的访问冲突读取位置

c - C中printf()函数的返回值

c - 使用套接字传输文件服务器/客户端 linux C

c - 什么时候在 GNU C 中使用分离线程?

synchronization - 信号量的共识数是多少?

c - 输入文件时出现 SegFault

c++ - 如何在 Qt 中检测 Windows 事件?

c++ - pthread_mutex_lock 上的段错误

c - 处理 pthread 以干净退出

c - 递归调用中 pthread 的段错误