我有一个程序,读取一些输入文本文件,所有的人都写到一个名为ListOutput
列表,它是在我的程序中使用的两个进程之间共享内存(我用了两个过程,所以我程序运行速度更快!)我也有叫processedFiles
共享内存变量,它由任何进程的存储已经读取输入文件的名称,因此目前的进程不会再次阅读!多处理锁()不工作
要确保两个进程不检查“processedFiles”在同一时间(例如,在开始的时候,它有可能在同一时间他们都可以得出的结论是,“processedFiles”是空的,所以他们读同一文件),因此,我添加了一个
Lock
各地检查一部分processedFiles
这样一个过程应该完成,而另一个过程中该部分检查之前释放锁定的一部分!我的问题是,
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']]
请张贴_complete_代码,甚至包括所需的import语句。试图猜测丢失的部分实在太烦人了,细节可能至关重要 - 如果它很明显,则不需要开始询问;-) –