2016-10-16 27 views
0

我有這個程序,要求用戶輸入一個數字來計算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);  
} 
+0

你知道那的'總和[1..1]''是((N + 1) * n)/ 2' – selbie

+0

這是打算作爲線程的嚴重用法,還是一個「玩具」的例子? – duskwuff

+0

@duskwuff玩具示例 –

回答

0

不用調用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) 

希望我幫助

+0

我試過,但我得到了分段錯誤 –

+0

編輯並從iNumber(在for循環中)中刪除了*,因爲它現在用作整數而不是指針。現在試試。 –

相關問題