I am implementing semaphore in c language.I have a POSIX counting semaphore. I want to assign a value to it. and i don't want to use Wait or Post. Can i do that? Is there any function like "setValue" for POSIX Semaphore ?
-
1[`sem_init(3)`](http://linux.die.net/man/3/sem_init) – Filipe Gonçalves Aug 24 '15 at 20:16
-
@FilipeGonçalves: Calling `sem_init` on an already-initialized semaphore results in undefined behavior. You could first destroy it, but if concurrent posts or waits are possible when you destroy it, that also results in undefined behavior. Basically what OP is asking for is just hopelessly wrong. – R.. GitHub STOP HELPING ICE Aug 25 '15 at 02:22
2 Answers
If you could directly change its value during normal operation (i.e. except for initialization), it would not be a semaphore anymore. So you might be looking for something different, maybe a thread-safe counter/shared variable? Such more complex shared objects are normaly implemented with the basic synchronization primitives, like locks/mutex/semaphore/etc. Which to use depends on what you want to implement.
OTOH, you are possibly presenting an XY-problem. Perhaps if you state what you actually want to achieve, we can point you to a better/easier/ solution.

- 1
- 1

- 12,050
- 4
- 30
- 52
Wait and Post are the only operations supported by a classic semaphore. POSIX semaphores can be initialized with a count using sem_init(). Any kind of 'setValue' function would destroy the functionality of the semaphore by allowing units to be 'lost', eg. by being posted by one thread just before 'setValue' was called by another.
It's a really bad idea, which is why it is not implemented.

- 24,453
- 3
- 36
- 60