C- Semaphore sem_getvalue not returning what I'm expecting?

此生再无相见时 提交于 2020-01-04 01:52:12

问题


I've been trying to get myself more acquainted with semaphores and was wondering why this code isn't printing the value I expect.

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

int main(int argc, char * argv[]) {
    sem_t sem;
    sem_init(&sem, 0, 1);
    int value;
    sem_getvalue(&sem, &value);
    printf("%d\n",value);

    return 0;
}

It prints 0 for the value. But from my understanding it should be getting the value I initialized the semaphore with which is 1? I tried using a semaphore in some code with pthreads and I initialized the semaphore with a value of 1, but when I called the sem_getvalue function it was printing 32767. Am I missing something here? Thanks in advance.

Edit: sem_init and sem_getvalue both return -1

Edit: Solved. It appears unnamed semaphores aren't implemented on Mac.


回答1:


I'm getting the output as expected. (i.e. 1)

try using linking with pthread library

gcc sema.c -lpthread



回答2:


It should return 1, which is the value you init,
when compile should add -pthread as option, e.g. gcc -pthread test.c

If the code runs well, then both sem_init() and sem_getvalue() should return 0,
if they return -1 then there is some error, you should get error flag, and check man page on linux to see what error happend.

By the way, your code return 1 on my linux, which is correct.
The man page: man sem_init and man sem_getvalue.
You should get error flag for sem_init(), then check man sem_init first, because the semaphore seems not properly created in the first place.




回答3:


Edit: Solved. It appears unnamed semaphores aren't implemented on Mac.

POSIX semaphore is considered as deprecated on Mac OSX. So, it doesn't work on it as expected.



来源:https://stackoverflow.com/questions/23146950/c-semaphore-sem-getvalue-not-returning-what-im-expecting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!