在 python 中的子进程之间共享锁

sharing Lock between subprocesses in python

我想知道如何在 python 子进程之间共享锁,这是我想做的一个简单示例(这不起作用:)

文件 1

import posix_ipc
import pickle
import multiprocessing as mp
flag = (posix_ipc.O_CREAT | posix_ipc.O_TRUNC | posix_ipc.O_RDWR)

mem = posix_ipc.SharedMemory("Mem", flags=flag, size=200)
mem = mmap.mmap(mem.fd, 200, mmap.MAP_SHARED, mmap.PROT_WRITE)

m = mp.Manager()
lock = m.Lock()
B_lock = pickle.dumps(lock)
B_len=len(B_lock)
mem[0:B_len]=B_lock
print(B_len)
length=int(input("enter the length"))
lock=pickle.loads(mem[0:length])
print(lock)
input()

文件 2

import posix_ipc
import multiprocessing as mp
import pickle

flag = 0

mem = posix_ipc.SharedMemory("Mem", flags=flag, size=200)

mem = mmap.mmap(mem.fd, 200, mmap.MAP_SHARED, mmap.PROT_WRITE)
length=int(input("enter the length"))
lock=pickle.loads(mem[0:length])
print(lock)

input()

共享内存工作完美,但每当我共享锁时,我都会收到以下错误消息

文件“/usr/lib/python3.8/multiprocessing/connection.py”,第 759 行,在 answer_challenge 提高 AuthenticationError('digest sent was rejected') multiprocessing.context.AuthenticationError: 发送的摘要被拒绝

多亏了这个 System-wide mutex in Python on Linux 我从中得到的是我要求的是系统范围的互斥锁,你可以通过使用 ilock 来实现它,这是我的例子

文件 1

from ilock import ILock

print("start this process first")
lock = ILock("VoidLock")
with lock:
    print("now this process inside, run the other procsses")
    input("enter anything so the other procsses can get inside the lock")

print("the lock is relased")

input()

文件 2

from ilock import ILock


lock = ILock("VoidLock")
print("now this process is witting")
with lock:
    print("now this process is inside ")
    input()

input()