我有一个程序,它读取一些输入文本文件并将它们全部写入一个名为ListOutput的列表中,这是程序中使用的两个进程之间的共享内存(我使用了两个进程,所以我的程序运行得更快!)我还有一个名为processedFiles的共享内存变量,它存储任何进程已经读取的输入文件的名称,这样当前进程就不会再读取它们了!
processedFiles的检查部分周围添加了一个Lock,以便在另一个进程签入到该部分之前,一个进程应该完成并释放锁定的部分!
我的问题是,Lock函数似乎不能工作,当我在锁部件中打印当前ProcessName时,它会显示两个进程都在锁部件内。我不知道我的代码出了什么问题?(见下面的输出。)Pool而不是Process吗?为什么?代码:
import glob
from multiprocessing import Process, Manager
from threading import *
import timeit
import os
os.chdir("files")
def print_content(ProcessName,processedFiles,ListOutput,lock):
for file in glob.glob("*.txt"):
newfile=0
lock.acquire()
print "\n Current Process:",ProcessName
if file not in processedFiles:
print "\n", file, " not in ", processedFiles," for ",ProcessName
processedFiles.append(file)
newfile=1#it is a new file
lock.release()
#if it is a new file
if newfile==1:
f = open(file,"r")
lines = f.readlines()
ListOutput.append(lines)
f.close()
# Create two processes as follows
try:
manager = Manager()
processedFiles = manager.list()
ListOutput = manager.list()
lock=Lock()
p1 = Process(target=print_content, args=("Procees-1",processedFiles,ListOutput,lock))
p2 = Process(target=print_content, args=("Process-2",processedFiles,ListOutput,lock))
p1.start()
p2.start()
p1.join()
p2.join()
print "ListOutput",ListOutput
except:
print "Error: unable to start process"我有4个输入文件,名为1.txt (包含“我的车”)、2.txt (包含“您的车”)、3.txt (包含“我的书”)、4.txt (包含“您的书”)。它向我展示的输出在不同的运行中发生了变化。这是其中一个运行中的输出:
Current Process: Procees-1
Current Process: Process-2
1.txt not in [] for Procees-1
Current Process: Procees-1
2.txt not in
Current Process: Process-2
['1.txt'] for Procees-1
2.txt not in ['1.txt', '2.txt'] for Process-2
Current Process: Procees-1
3.txt not in ['1.txt', '2.txt', '2.txt'] for Procees-1
Current Process: Process-2
Current Process: Process-2
4.txt not in
Current Process: Procees-1
['1.txt', '2.txt', '2.txt', '3.txt'] for Process-2
4.txt not in ['1.txt', '2.txt', '2.txt', '3.txt', '4.txt'] for Procees-1
ListOutput [['my car'], ['your car'], ['your car'], ['my book'], ['your book'], ['your book']]发布于 2016-10-08 00:48:04
对啰!谢谢你把进口商品包括在内。现在问题很明显;-)
您需要使用multiprocessing.Lock来获得跨进程工作的锁。您实际使用的Lock是通过您的
from threading import *threading.Lock对您的目的是无用的:它对进程没有任何影响;它只在单个进程中提供线程间的排除。
使用import *通常是个坏主意,这也是原因之一。即使您将第二个导入更改为
from multiprocessing import Process, Manager, Lock
^^^^这对您没有任何好处,因为from threading import *会覆盖您真正想要的Lock。
https://stackoverflow.com/questions/39927405
复制相似问题