fcntl() for thread or process synchronization?

一个人想着一个人 提交于 2019-12-12 14:07:43

问题


Is it possible to use fcntl() system call on a file to achieve thread/process synchronization (instead of semaphoress)?


回答1:


Yes. Unix fcntl locks (and filesystem resources in general) are system-wide, so any two threads of execution (be they separate processes or not) can use them. Whether that's a good idea or not is context-dependent.




回答2:


That's one way of synchronizing between processes, but if you don't want to use semaphores, you could use process shared mutexes, such as mutexes and condition variables created with the PTHREAD_PROCESS_SHARED attribute on POSIX based platforms (see pthread_mutexattr_setpshared() and pthread_condattr_setpshared()). Another option is to use an event based IPC (sockets, etc) mechanism that blocks until an event you define is demultiplexed (e.g. via select()). There are several other shared memory based options as well.

However, since you're using C++ I'd recommend using a C++ framework that greatly simplifies this sort of interprocess synchronization across multiple platforms like boost.interprocess or ACE.




回答3:


The fcntl and flock are not for thread, but for process, so they cannot be used for thread synchronization.



来源:https://stackoverflow.com/questions/1765301/fcntl-for-thread-or-process-synchronization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!