开发者

*nix System-wide threads and processes mutex

开发者 https://www.devze.com 2023-01-06 06:12 出处:网络
I have some resource which I\'d like to protect from concurrent usage both by threads in the same process and among different processes.

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 m开发者_如何学Cemory 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消