簡體   English   中英

線程編程…端子無輸出

[英]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){

由於MAX_LEN為且保持非零。

至於為什么之前看不到任何輸出,請參閱為什么在調用之后除非換行符在格式字符串中,否則printf不會刷新?

您的線程函數中有一個無限循環:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM