2016-03-01 94 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