2013-10-13 99 views
-1

我在做多線程編程,並試圖實現蒙特卡洛技術在其計算PI值無輸出。我編譯的代碼,我沒有錯誤,但是當我執行我沒有得到任何輸出它。請糾正我,如果有任何錯誤。線程編程......在終端

這裏是我的代碼:

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

#define frand() ((double) rand()/(RAND_MAX)) 
#define MAX_LEN 1353 
const size_t N = 4; 
float circlePoints=0; 
void* point_counter(void *param){ 
    float xcord; 
    float ycord; 
    while(MAX_LEN){ 

     xcord=frand(); 
     ycord=frand(); 
     float cord = (xcord*xcord) + (ycord*ycord); 

     if(cord <= 1){ 
      circlePoints++;} 
    } 
} 

int main() 
{ 
    printf("out"); 
    size_t i; 
    pthread_t thread[N]; 

    srand(time(NULL)); 
    for(i=0;i <4;++i){ 
     printf("in creating thread"); 
     pthread_create(&thread[i], NULL, &point_counter, NULL); 
    } 
    for(i=0;i <4;++i){ 
     printf("in joining thread"); 
     pthread_join(thread[i], NULL); 
    } 
    for(i=0;i <4;++i){ 
     printf("in last thread"); 
     float pi = 4.0 * (float)circlePoints /MAX_LEN; 

     printf("pi is %2.4f: \n", pi); 
    } 
    return 0; 
} 
+1

通過無輸出,你的意思是它在一個無限循環中運行? – 2013-10-13 08:13:40

+1

有你,儘管有關使用調試?它很容易顯示無限循環 –

回答

2

你有一個無限循環在你的線程函數:

while(MAX_LEN){ 
    ... 
} 

因此,所有的線程,你創造永不走出這個循環。

此外,circlePoints是由所有的線程這將導致競爭條件what's a race condition?),並有可能呈現不正確的值修改。你應該使用互斥鎖來避免它。

1
while(any_non_zero_number_which does_not_update) 
{ 
    infinite loop   //not good unless you intend it that way 
}