[英]Thread Programming… No output in terminal
我正在執行線程編程,並嘗試實現MonteCarlo技術來計算其中的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;
}
您的線程函數中有一個無限循環:
while(MAX_LEN){
...
}
因此,您創建的所有線程都永遠不會退出該循環。
而且,所有線程都會修改circlePoints
,這將導致競爭條件 ( 什么是競爭條件? ),並可能導致值不正確。 您應該使用互斥鎖來避免這種情況。
while(any_non_zero_number_which does_not_update)
{
infinite loop //not good unless you intend it that way
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.