2016-03-01 70 views
0

我嘗試編寫關於信號量的問題,問題是Xcode的輸出不是按照正確順序排列的。我認爲這是因爲'printf()'函數緩衝區。我在Xcode中給出了代碼和結果。有一些代碼部分,如'for(int i = 0; i < 10000; i ++)',以加強互斥和數據損壞。這裏是代碼:Xcode C編程 - 輸出順序錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <semaphore.h> 

#define NUM_THREADS 3 
int ctr = 0; 

sem_t sem; 

void *IncCounter(); 

int main(void) { 

    int ret_value; 
    pthread_t threads[NUM_THREADS]; 
    sem_init(&sem, 0, 1); 

    for(int t=0; t<NUM_THREADS; t++){ 
     ret_value=pthread_create(&threads[t], NULL, IncCounter, NULL); 
    } 
    pthread_exit(NULL); 
} 

void *IncCounter(){ 
    for (int l=0; l<5; l++) { 
     sem_wait(&sem); 
     ++ctr; 
     for (int i=0; i<10000; i++) { 

      } 
     printf("Counter is: %d\n", ctr); 
     sem_post(&sem); 
    } 
    pthread_exit(NULL); 
    return NULL; 
} 

我現在給我從Xcode的輸出。

Counter is: 3 
Counter is: 3 
Counter is: 3 
Counter is: 6 
Counter is: 7 
Counter is: 8 
Counter is: 9 
Counter is: 10 
Counter is: 10 
Counter is: 12 
Counter is: 13 
Counter is: 14 
Counter is: 14 
Counter is: 14 
Counter is: 15 
Program ended with exit code: 0 

我該如何避免這種情況?非常感謝閱讀,

梅特

+0

線程函數的簽名是錯誤的,應該是'void * foo(void *)'。編譯器最有可能消除循環的「延遲」,使用「睡眠」函數來獲得延遲。你正在用'-pthread'編譯(和鏈接)嗎? – Mat

+0

請解釋您預期的順序,以及爲什麼。 –

+0

注意你的* main()*線程應該等待其子線程運行結束。 – tofro

回答

-1

代碼看起來確定,所以它真的有可能下降到printf的緩衝區。嘗試在printf後添加fflush(stdout);

+0

我認爲你既沒有理解程序的輸出,也沒有理解'printf'在遇到'\ n'時輸出描述符是設備終端時自動'fflush()'的行爲。 –

+0

完全同意,「fflush(stdout)」不影響任何內容。 – EMI