Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xcode C编程-输出顺序错误_C_Xcode_Output_Mutex - Fatal编程技术网

Xcode C编程-输出顺序错误

Xcode C编程-输出顺序错误,c,xcode,output,mutex,C,Xcode,Output,Mutex,我试图编写有关信号量的程序,问题是Xcode的输出顺序不正确。我认为这是因为'printf()'函数缓冲区。我在Xcode中给出了代码和结果。有一些代码部分像'for(int i=0;如果线程函数的签名错误,则应该是void*foo(void*)。编译器很可能会消除循环的“延迟”,请使用sleep-类型的函数来获得延迟。您正在编译(和链接)吗使用-pthread?请解释您期望的顺序以及原因。请注意,您的main()线程应该等待其子线程运行结束。1)我更改了签名,但它是相同的。另外,使用“for循

我试图编写有关信号量的程序,问题是Xcode的输出顺序不正确。我认为这是因为'printf()'函数缓冲区。我在Xcode中给出了代码和结果。有一些代码部分像'for(int i=0;如果线程函数的签名错误,则应该是
void*foo(void*)
。编译器很可能会消除循环的“延迟”,请使用
sleep
-类型的函数来获得延迟。您正在编译(和链接)吗使用
-pthread
?请解释您期望的顺序以及原因。请注意,您的main()线程应该等待其子线程运行结束。1)我更改了签名,但它是相同的。另外,使用“for循环”时,我尝试让线程保持忙碌状态,以查看一些可能的中断。但当我写'sleep'而不是'for'来保持系统繁忙时,它将是一个'suspended thread'。2)顺序应该是'Counter is:1'到'Counter is:15',没有任何重复。
#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;
}
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