python编程解决排队问题_并行排队多处理池,python

我的目标是遍历一个目录并计算其中所有文件的MD5。我用代码来解决类似的问题import os

import re

import sys

import time

import md5

from stat import S_ISREG

import multiprocessing

global queue

size_limit = 500000

target = sys.argv[1]

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

############Analysis and Multiprocessing####################

def walk_files(topdir):

"""yield up full pathname for each file in tree under topdir"""

for dirpath, dirnames, filenames in os.walk(topdir):

for fname in filenames:

pathname = os.path.join(dirpath, fname)

yield pathname

def files_to_search(topdir):

"""yield up full pathname for only files we want to search"""

for fname in walk_files(topdir):

try:

# if it is a regular file and big enough, we want to search it

sr = os.stat(fname)

if S_ISREG(sr.st_mode) and sr.st_size <= size_limit:

yield fname

except OSError:

pass

def worker_search_fn(fname):

fp = open(fname, 'rt')

# read one line at a time from file

contents = fp.read()

hash = md5.md5(contents)

global queue

print "enqueue"

queue.put(fname+'-'+hash.hexdigest())

################MAIN MAIN MAIN#######################

################MAIN MAIN MAIN#######################

################MAIN MAIN MAIN#######################

################MAIN MAIN MAIN#######################

################MAIN MAIN MAIN#######################

#kick of processes to md5 the files and wait till completeion

queue = multiprocessing.Queue()

pool = multiprocessing.Pool()

pool.map(worker_search_fn, files_to_search(target))

pool.close()

pool.join()

#Should be done, now lets send do our analysis

while not queue.empty():

print queue.get()

我添加了“print enqueue”语句作为调试目的,我注意到代码确实在递归一个大目录树时锁定了。我不确定两个进程是否试图同时访问队列,从而导致死锁。在

也许有更好的方法来做这件事?该结构不必是队列,但必须是无锁的,以便充分利用多处理。我想要一个递归和md5并行的目录,一旦完成,就把列表作为一个整体来做一些事情。为了调试,我只打印完成的队列。有什么建议吗?在

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值