2014-10-11 19 views
0

所以我有兩個線程。一個是數學,另一個是數學的結果。有時,結果線程首先出現,並顯示0而不是有效的結果。我怎樣才能防止這一點?我可以確保某個線程總是最後工作,沒有信號量嗎?

void *math (void *arg); 
void *result(void *arg); 

int a; 

int main(int argc, char *argv[]) { 
    pthread_t mathT; 
    pthread_t resultT; 

    pthread_create(&mathT, NULL, math, NULL); 
    pthread_create(&resultT, NULL, result, NULL); 

    pthread_join(mathT, NULL); 
    pthread_join(resultT, NULL); 

    return 0; 
} 

void *math(void *arg) { 
    a = 9 + 9; 
    return NULL; 
} 

void *result(void *arg) { 
    printf("%d", a); 
    return NULL; 
} 
+2

什麼是有兩個線程,然後點?只需一個線程即可調用這兩個函數。 – 2014-10-11 03:00:30

+0

這不是重點。當然,我可以連續做到這一點,但不,我必須使用單獨的線程。 – user2837858 2014-10-11 03:01:29

+1

把'pthread_join(mathT)'放在'pthread_create(resultT)'之前。 – user3386109 2014-10-11 03:11:04

回答

0

調用pthread_cond_wait()阻止當前線程,然後使用調用pthread_cond_signal()或調用pthread_cond_broadcast()即可喚醒

相關問題