python多线程实现为阻塞语句计时

python多线程实现为阻塞语句计时,第1张

os.system默认阻塞当前程序执行,在cmd命令前加入start可不阻塞当前程序执行。

例如:

import os

os.system(r"start E:\TX\qq.exe")

或者

os.system('start python test.py ')

在前面的例子里学习了并发地执行多个协程来下载图片,也许其中一个协程永远下载不了,一直阻塞,这时怎么办呢?

碰到这种需求时不要惊慌,可以使用wait()里的timeout参数来设置等待时间,也就是从这个函数开始运行算起,如果时间到达协程没有执行完成,就可以不再等它们了,直接从wait()函数里返回,返回之后就可以判断那些没有执行成功的,可以把这些协程取消掉。例子如下:

[python] view plain copy

import asyncio

async def phase(i):

print('in phase {}'.format(i))

try:

await asyncio.sleep(0.1 * i)

except asyncio.CancelledError:

print('phase {} canceled'.format(i))

raise

else:

print('done with phase {}'.format(i))

return 'phase {} result'.format(i)

async def main(num_phases):

print('starting main')

phases = [

phase(i)

for i in range(num_phases)

]

print('waiting 0.1 for phases to complete')

completed, pending = await asyncio.wait(phases, timeout=0.1)

print('{} completed and {} pending'.format(

len(completed), len(pending),

))

# Cancel remaining tasks so they do not generate errors

# as we exit without finishing them.

if pending:

print('canceling tasks')

for t in pending:

t.cancel()

print('exiting main')

event_loop = asyncio.get_event_loop()

try:

event_loop.run_until_complete(main(3))

finally:

event_loop.close()

结果输出如下:

starting main

waiting 0.1 for phases to complete

in phase 0

in phase 2

in phase 1

done with phase 0

1 completed and 2 pending

canceling tasks

exiting main

phase 1 canceled

phase 2 canceled

setblocking(0)之后就是非阻塞的。 select模块只是说能够同时处理多个socket,至于这些socket是阻塞还是非阻塞,都没有关系。当然从性能上考虑,现在的趋势是select+非阻塞。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11335746.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存