Pregunta

I have some problems in understanding the output of the following Code-Example.

int main(int argc, char *argv[]) {
sem_t *mutex_init;
int i = 0, mutex_value;
mutex_init = sem_open("/Semaphore", O_CREAT, 0644, 1);
for(i = 0; i < 10; i++) {
    if(sem_getvalue(mutex_init, &mutex_value) < 0) {
        perror("sem_getvalue() failed");
        exit(EXIT_FAILURE);
    }
    printf("mutex_value: %d\n",mutex_value);fflush(stdout);
    if(sem_wait(mutex_init) < 0) {
        perror("sem_wait() failed");
        exit(EXIT_FAILURE);
    }
    if(sem_getvalue(mutex_init, &mutex_value) < 0) {
        perror("sem_getvalue() failed");
        exit(EXIT_FAILURE);
    }
    printf("mutex_value: %d\n",mutex_value);fflush(stdout);
    if(sem_post(mutex_init) < 0) {
        perror("sem_post() failed");
        exit(EXIT_FAILURE);
    }
    printf("mutex_value: %d\n",mutex_value);fflush(stdout);
    printf("------\n");
}
return EXIT_SUCCESS;
}

I have got the following output

    mutex_value: 1
    mutex_value: 0
    mutex_value: 0
    ------
    mutex_value: 1
    mutex_value: 0
    mutex_value: 0

but expected something like that

    mutex_value: 1
    mutex_value: 0
    mutex_value: 1
    -------
    ...

Iam not sure, but perhaps this is because "buffered output" or anything else?

Thanks for help.

¿Fue útil?

Solución

You do not call sem_getvalue after sem_post, so mutex_value has a stale value.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top