使用Python多处理在工作人员之间共享变量
如何读取和更新Python中多个工作线程之间共享的变量 例如,我正在使用Python中的多个进程扫描文件列表,并希望检查父目录是否已被扫描使用Python多处理在工作人员之间共享变量,python,multiprocessing,python-multithreading,Python,Multiprocessing,Python Multithreading,如何读取和更新Python中多个工作线程之间共享的变量 例如,我正在使用Python中的多个进程扫描文件列表,并希望检查父目录是否已被扫描 def readFile(filename): """ Add the parent folder to the database and process the file """ path_parts = os.path.split(filename) dirname = os.path.basename(path_parts[0])
def readFile(filename):
""" Add the parent folder to the database and process the file
"""
path_parts = os.path.split(filename)
dirname = os.path.basename(path_parts[0])
if dirname not in shared_variable:
# Insert into the database
#Other file functions
def main():
""" Walk through files and pass each file to readFile()
"""
queue = multiprocessing.Queue()
pool = multiprocessing.Pool(None, init, [queue])
for dirpath, dirnames, filenames in os.walk(PATH):
full_path_fnames = map(lambda fn: os.path.join(dirpath, fn),
filenames)
pool.map(readFile, full_path_fnames)
看一看。您可以使用共享内存使用
Value
或Array
在两个或多个线程之间共享数据。您可以使用multiprocessing.Manager
进行帮助。它允许您创建可在进程之间共享的列表:
from functools import partial
import multiprocessing
def readFile(shared_variable, filename):
""" Add the parent folder to the database and process the file
"""
path_parts = os.path.split(filename)
dirname = os.path.basename(path_parts[0])
if dirname not in shared_variable:
# Insert into the database
#Other file functions
def main():
""" Walk through files and pass each file to readFile()
"""
manager = multiprocessing.Manager()
shared_variable = manager.list()
queue = multiprocessing.Queue()
pool = multiprocessing.Pool(None, init, [queue])
func = partial(readFile, shared_variable)
for dirpath, dirnames, filenames in os.walk(PATH):
full_path_fnames = map(lambda fn: os.path.join(dirpath, fn),
filenames)
pool.map(func, full_path_fnames)
partial
只是用来更容易地将shared\u变量
传递给readFile
的每个调用,以及full\u path\fnames的每个成员
通过map这比您想象的要难解决。直接的答案是,您可以与multiprocessing.Manager
共享可变状态,但如果不实现某种互斥锁条件,您将面临一些严重的竞争条件。如果可能的话,重构您的代码,使您的工作人员完全不依赖于共享状态。