Use a POSIX semaphore initialized to 1
instead. (See below) Use sem_init
for unnamed semaphores or sem_open
for named ones.
sem_t sem;
/* initialize using sem_init or sem_open */
sem_wait(&sem);
/* critical region */
sem_post(&sem);
Many years after initially posting this answer, it has to be updated.
Mutexes should actually be used instead of semaphores. R and kuga's comments (copied verbatim below) explain why. In particular I find kuga's mention that mutexes can only be post
ed by their locking thread most compelling.
R
sem_init requires a nonzero pshared argument to be shared, just like a
mutex would require the pshared attribute. There's no reason to prefer
semaphores over mutexes for this, and in fact mutexes would be better
because you could use a robust mutex which allows you to handle the
(very real!) case where one process dies while holding the lock.
kuga
Additionally to R..`s post, a mutex can only be posted by the thread
that locks it. This is often required and a semaphore does not provide
this feature. So this is not the correct answer, Jeff′s answer should
be flagged as the correct answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…