不相关的流程如何使用futex进行合作?
假设我有不相关的进程,例如,一个是带有我的模块的apache子进程,另一个例如是后台脚本.
我想使用futex在两者之间建立一个带有互斥的条件变量,以便为用户空间快速代码路径带来好处.
在我看来,存储互斥锁的存储器可以在mmap的文件中,如果该存储器被映射,mlock’d这两个进程理论上可以针对相同的地址发出futex调用.
或者,也许可以使用FUTEX_FD将futex从一个进程传递到另一个进程.
代码提交接受低级,高级和动态语言(C,C,Python等).还必须支持“robust futex”API.
参考文献:
> https://www.kernel.org/doc/Documentation/robust-futexes.txt
> http://locklessinc.com/articles/mutex_cv_futex/
最佳答案
感谢Phillip和Felix M.指针.
Python用户代码(已存在数据结构的文件,使用PTHREAD_PROCESS_SHARED初始化)
with open("/tmp/semaphore","rb+") as f:
m = mmap.mmap(f.fileno(),0) # default: all file,share,read-write
data = ffi.cast("unsigned long[3]",id(m))[2] # pointer to mapped area,64-bit CPython
lock = ffi.cast("pthread_mutex_t *",data)
cond = ffi.cast("pthread_cond_t *",data + 40)
@contextlib.contextmanager
def locked(alock):
assert not C.pthread_mutex_lock(alock)
try:
yield
finally:
assert not C.pthread_mutex_unlock(alock)
等等醒来:
if "wait" in sys.argv:
with locked(lock):
assert not C.pthread_cond_wait(cond,lock)
elif "signal" in sys.argv:
with locked(lock):
assert not C.pthread_cond_signal(cond)
设置PTHREAD_PROCESS_SHARED的基础知识:
l = ffi.new("pthread_mutexattr_t *")
assert not C.pthread_mutexattr_init(l)
assert not C.pthread_mutexattr_setpshared(l,1) # PTHREAD_PROCESS_SHARED
assert not C.pthread_mutex_init(lock,l)
# same for condition variable
针对nitpicks的完整代码:-) https://github.com/dimaqq/pthread_mutexattr_init/blob/master/xsem.py基于http://linux.die.net/man/3/pthread_mutexattr_init