我想在Python中使用多处理库来同时处理“测试”。我有一个存储在变量test_files
中的测试列表。我想要工人从test_files
中删除一个测试,并调用它们的process_test
函数。但是,当我运行此代码时,两个进程都运行相同的测试。似乎我没有以线程安全的方式访问test_files
。我究竟做错了什么?Python锁定关键部分
代码
def process_worker(lock, test_files)
# Keep going until we run out of tests
while True:
test_file = None
# Critical section of code
lock.acquire()
try:
if len(test_files) != 0:
test_file = test_files.pop()
finally:
lock.release()
# End critical section of code
# If there is another test in the queue process it
if test_file is not None:
print "Running test {0} on worker {1}".format(test_file, multiprocessing.current_process().name)
process_test(test_file)
else:
# No more tests to process
return
# Mutex for workers
lock = multiprocessing.Lock()
# Declare our workers
p1 = multiprocessing.Process(target = process_worker, name = "Process 1", args=(lock, test_files))
p2 = multiprocessing.Process(target = process_worker, name = "Process 2", args=(lock, test_files))
# Start processing
p1.start()
p2.start()
# Block until both workers finish
p1.join()
p2.join()
输出
Running test "BIT_Test" on worker Process 1
Running test "BIT_Test" on worker Process 2
我认为它的,因为你是在复制它传递给新进程的进程列表。它需要某种共享项目,如[Value](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Value)或[Array](https://docs.python.org/2 /library/multiprocessing.html#multiprocessing.Array)。它们都是'multiprocessing'模块的一部分。另请参阅https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes –