1
votes

What I'm currently working on requires a couple of posix semaphores to be initialized inside of a function that multiple processes will be running, and the semaphores will be shared with another function where those processes will also be running. How do I go about this so that the semaphores are only created once by one thread, while the rest only open them? I can't seem to find anything about how to do this anywhere.

All I can find on the subject is about how to use the sem_wait() and sem_post() functions, but nothing specific to my problem. I also had to make sure that a file was created only once and opened by the other processes, but the file can be checked whether or not it's been created already by the access() function. Is there anything like that for semaphores?

Any help in explaining how this is done would be greatly appreciated.

1
Create them outside the threads before starting them.Fredrik

1 Answers

0
votes

the file can be checked whether or not it's been created already by the access() function

It only appears that it can be so checked. In reality this doesn't work.

A file can be created another thread of execution just after you have verified it doesn't exist by calling access(), and before you try creating it yourself. This is called a race condition.

This is why one uses O_EXCL | O_CREAT flags in the open and sem_open system calls. This operation is atomic: it verifies that the file/semaphore doesn't exists, and creates a new one, in one indivisible action. If the action returns a failure and errno is set to EEXIST, the file/semaphore already exists.

This naturally works only for named semaphores (those you create with sem_open). An unnamed semaphore (one you create with sem_init) should be created before starting threads that use it, or its creation should be synchronised by other means.