views:

33

answers:

2

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.

A: 

If the resource is global and shared access is desired, you must use locks. If it is thread-local, use thread-local storage. If it can be local, use a local object.

Philipp
Thanks for your answer, but it is too broad, I asked how to do locks which can lock both other threads and processes out of a critical section, and I was talking about a global resource of course.
Metiu
AFAIK all types of synchronization primitives like mutexes and semaphores lock both other threads and other processes.
Philipp
+1  A: 

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.

Nikolai N Fetissov
+1 Named POSIX sems in particular are accessible inter- and intra-process (and the API is relatively easy, too).
pilcrow