views:

34

answers:

3

With reference to the semaphore implementation of semaphore.h in Linux, does an uninitialized semaphore sem_t default to 0?

I just discovered that I had forgotten to initialize my semaphores to 0. Even so, the program worked fine without sem_init.

(To all the purists, I completely agree that doing so is a bad practice.)

+2  A: 

I believe it is officially 'undefined'. That is, it could be anything. In your case, for some reason, it happens to be coming up 0, but that's just luck. Tomorrow it may be 5.

Michael Kohne
+2  A: 

It will depend on how/where the semaphore is defined.

  • If it is defined as (part of) a global variable, then the compiler must initialise it to 0 if you don't specify any value
  • This is also true when it is (part of) a block-scope variable declared as static.
  • If it is (part of) a non-static block-scope variable, then it will start out with whatever value has been previously stored in that memory location.
Bart van Ingen Schenau
+1  A: 

This depends on the compiler, rather than the operating system/semaphore implementation. Bart's answer covers the C standard in this case.

However, according to the Unix standard, you shouldn't even rely on a sem_t being 0, or even a sem_t * being NULL; using sem_init on an unitialized variable should be safe. The only special value specified for semaphores is the sem_t * value SEM_FAILED and its value is implementation-specific.

larsmans