gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:56:03 25 4
gpt4 key购买 nike

我有一个程序,要求用户输入一个数字来计算 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com