I have some resource which I’d like to protect from concurrent usage both by threads in the same process and among different processes.
What is the “right” way of doing it in *nix?
E.g. we want to write to a file from a multithreaded app, which once in a while forks some subprocesses. How to ensure that each thread has exclusive access to the file for some time? I’m looking for a general answer, not something that works only for writing to a file, since it may also be a shared memory segment etc.
Too general of a question, thus a general answer.
The most flexible synchronization facility would probably be POSIX semaphores. There’s also old and cumbersome SysV IPC semaphore mechanism, which you might have to use instead depending on platform support.
You might also want to look into PTHREAD lock attributes to see if your platform supports shared semantics.