相关疑难解决方法(0)

我将如何使用concurrent.futures和队列进行实时场景?

使用Python 3的concurrent.futures模块进行并行工作相当容易,如下所示.

with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    future_to = {executor.submit(do_work, input, 60): input for input in dictionary}
    for future in concurrent.futures.as_completed(future_to):
        data = future.result()  
Run Code Online (Sandbox Code Playgroud)

将项目插入和检索到队列中也非常方便.

q = queue.Queue()
for task in tasks:
q.put(task)
while not q.empty():
   q.get()
Run Code Online (Sandbox Code Playgroud)

我有一个在后台运行的脚本,用于监听更新.现在,理论上假设,当这些更新到达时,我会将它们排队并使用它们同时处理它们ThreadPoolExecutor.

现在,单独地说,所有这些组件都是孤立的,并且有意义,但我如何一起使用它们呢?我不知道是否可以ThreadPoolExecutor实时从队列中提取工作,除非预先确定的数据是什么?

简而言之,我想做的就是,每秒接收4条消息的更新,将它们推入队列,然后让我的concurrent.futures对它们进行处理.如果我不这样做,那么我会陷入一种缓慢的顺序方法.

我们来看下面Python文档中的规范示例:

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r …
Run Code Online (Sandbox Code Playgroud)

python queue concurrency multithreading python-3.x

11
推荐指数
2
解决办法
5006
查看次数

标签 统计

concurrency ×1

multithreading ×1

python ×1

python-3.x ×1

queue ×1