Python-ThreadPoolExecutor阻止.如何解除封锁 [英] Python - ThreadPoolExecutor blocking. How to unblock

查看:740
本文介绍了Python-ThreadPoolExecutor阻止.如何解除封锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码被阻止:

import threading
from concurrent.futures import ThreadPoolExecutor
import os
from pprint import pprint
import time


def sleep(seconds):
    for i in range(seconds):
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            continue


def get_instance():
    return threading.current_thread()


def handle_instance(h):
    pprint("Got instance " + str(h.result()))
    sleep(6)


def task():
    print("Executing our Task on Process: {}".format(os.getpid()))


def main():
    with ThreadPoolExecutor(1) as th_exec:
        th_future = th_exec.submit(get_instance)
        th_future.add_done_callback(handle_instance)


if __name__ == "__main__":
    while True:
        main()
        sleep(1)

我希望6秒钟后,少数线程会立即输出.这没有发生.不确定如何管理或忘记了什么.

I expect that after 6 seconds, a handful of threads would have output at once. This did not happen. Not sure how I managed this or what I'm forgetting here.

推荐答案

由于未启动a handful of threads,因此不会获得预期的输出a handful of threads would have output at once.您一次只能创建一个线程来执行单个任务,这是对get_instance()函数的调用.

You don't get expected output a handful of threads would have output at once because you don't start a handful of threads. You create only one thread at a time to perform a single task which is a call of get_instance() function.

使用以下代码,您可能会获得接近所需输出的结果:

You may get something close to the desired output with following code:

import datetime as dt
from concurrent.futures import ThreadPoolExecutor
import os
import threading
import time


def handle_instance(h):
    t = dt.datetime.time(dt.datetime.now())
    print('[{}] Got instance {}'.format(t, h))
    print('[{}] Result is {}'.format(t, h.result()))
    print(id(t))


def task():
    print("Executing our Task on Process: {}".format(os.getpid()))
    time.sleep(3)
    return 1


def main():
    with ThreadPoolExecutor(3) as th_exec:
        for dummy in range(3):
            th_future = th_exec.submit(task)
            th_future.add_done_callback(handle_instance)


if __name__ == "__main__":
    try:
        while True:
            print('A new cycle of execution just started...')
            threading.Thread(target=main, daemon=True).start()
            time.sleep(5)
    except KeyboardInterrupt:
        raise SystemExit('\nexit by user')

输出:

A new cycle of execution just started...
Executing our Task on Process: 2528
Executing our Task on Process: 2528
Executing our Task on Process: 2528
[10:40:19.100711] Got instance <Future at 0x262342a9320 state=finished returned int>
[10:40:19.100711] Got instance <Future at 0x2623425e128 state=finished returned int>
[10:40:19.100711] Result is 1
[10:40:19.100711] Result is 1
[10:40:19.100711] Got instance <Future at 0x26233fe3ef0 state=finished returned int>
[10:40:19.100711] Result is 1

exit by user

这篇关于Python-ThreadPoolExecutor阻止.如何解除封锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆