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