小编ris*_*ado的帖子

Python:如何将外部队列与 ProcessPoolExecutor 一起使用?

我最近开始使用 Python 的多线程和多处理功能。

我尝试编写代码,使用生产者/消费者方法从 JSON 日志文件中读取块,将这些块作为事件写入队列,然后启动一组进程,这些进程将从该队列(文件块)中轮询事件并处理每个其中之一,打印出结果。

我的意图是首先启动进程,让它们等待事件开始进入队列。

我目前正在使用这段代码,它似乎可以工作,使用我发现的示例中的一些点点滴滴:

import re, sys
from multiprocessing import Process, Queue

def process(file, chunk):
    f = open(file, "rb")
    f.seek(chunk[0])
    for entry in pat.findall(f.read(chunk[1])):
        print(entry)

def getchunks(file, size=1024*1024):
    f = open(file, "rb")
    while True:
        start = f.tell()
        f.seek(size, 1)
        s = f.readline() # skip forward to next line ending
        yield start, f.tell() - start
        if not s:
            break

def processingChunks(queue):
    while True:
        queueEvent = queue.get()
        if (queueEvent == None):
            queue.put(None)
            break
        process(queueEvent[0], queueEvent[1])

if __name__ == …
Run Code Online (Sandbox Code Playgroud)

python asynchronous multiprocessing

5
推荐指数
1
解决办法
3517
查看次数

标签 统计

asynchronous ×1

multiprocessing ×1

python ×1