我有這個程序,要求用戶輸入一個數字來計算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);
}
你知道那的'總和[1..1]''是((N + 1) * n)/ 2' – selbie
這是打算作爲線程的嚴重用法,還是一個「玩具」的例子? – duskwuff
@duskwuff玩具示例 –