美国封锁python_Python-ThreadPoolExecutor阻止。如何解除封锁

本文通过一个示例代码展示了如何使用Python的`concurrent.futures`模块创建线程池来并行执行任务。原始代码仅创建了一个线程执行单一任务,而修改后的代码创建了三个线程,每个线程执行`task`函数,实现了并行处理,输出了预期的多线程同时输出。重点讨论了线程池的使用和多线程并行执行的概念。
摘要由CSDN通过智能技术生成

The following code is blocking:

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)

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.

解决方案

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')

Output:

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

[10:40:19.100711] Got instance

[10:40:19.100711] Result is 1

[10:40:19.100711] Result is 1

[10:40:19.100711] Got instance

[10:40:19.100711] Result is 1

exit by user

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值