python线程池wait_Python中的time.sleep和多线程问题

进行非阻塞等待的一种方法是使用threading.Event:

import threading

dummy_event = threading.Event()

dummy_event.wait(timeout=1)

可以从另一个线程进行set()来指示已完成某些操作.但是,如果您要在另一个线程中执行操作,则可以完全避免超时和事件,而只需加入另一个线程即可:

import threading

def create_the_file(completion_event):

# Do stuff to create the file

def Main():

worker = threading.Thread(target=create_the_file)

worker.start()

# We will stop here until the "create_the_file" function finishes

worker.join()

# Do stuff with the file

如果您想要使用事件进行更细粒度控制的示例,我可以向您展示…

如果您的平台不提供线程模块,则线程方法将不起作用.例如,如果您尝试替换dummy_threading模块,则dummy_event.wait()将立即返回.不确定join()方法.

如果您正在等待其他进程完成,最好使用subprocess模块(然后,例如,使用wait方法来确保已完成该过程,然后再执行其他工作)从自己的脚本管理它们.

如果您无法通过脚本管理子流程,但知道PID,则可以使用os.waitpid()函数.如果在使用此功能时该过程已经完成,请当心OSError.

目录监视的快速示例代码:

import gio

def directory_changed(monitor, file1, file2, evt_type):

print "Changed:", file1, file2, evt_type

gfile = gio.File(".")

monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)

monitor.connect("changed", directory_changed)

import glib

ml = glib.MainLoop()

ml.run()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以用线程实现,但需要注意以下几点: 1. 在多线程使用 time.sleep() 会阻塞整个线程,因此需要使用 threading.Event() 或者 concurrent.futures 库wait() 方法来进行等待。 2. 需要使用线程安全的队列来进行任务的交换,以保证线程之间的同步。 3. 在多线程使用 asyncio 库需要使用 run_in_executor() 方法来在新的线程执行协程任务。 下面是使用线程实现的代码示例: ```python import threading import time import asyncio from concurrent.futures import ThreadPoolExecutor def send_doip_request(): # 这里模拟发送 doip 请求的过程,实际应用需要根据具体协议实现 print("Sending DOIP request...") time.sleep(2) # 模拟等待回复的过程 print("Received DOIP response") async def main(): # 创建一个协程任务,表示发送 doip 请求 doip_task = asyncio.create_task(send_doip_request()) try: # 等待 doip 请求完成,最长等待时间为 3 秒 await asyncio.wait_for(doip_task, timeout=3) except asyncio.TimeoutError: # 如果超时未收到回复,则取消任务并重新发送请求 print("Timeout! Resending DOIP request...") # 使用线程池执行 send_doip_request() 函数 with ThreadPoolExecutor() as executor: future = executor.submit(send_doip_request) try: asyncio.get_event_loop().run_until_complete(asyncio.wait_for(future, timeout=3)) except asyncio.TimeoutError: future.cancel() time.sleep(1) # 等待一段时间,模拟重新发送请求的过程 future = executor.submit(send_doip_request) asyncio.get_event_loop().run_until_complete(asyncio.wait_for(future, timeout=3)) asyncio.run(main()) ``` 需要注意的是,在线程执行协程任务时,需要使用 asyncio.get_event_loop().run_until_complete() 方法来进行调用。同时,由于线程无法使用 asyncio.sleep(),因此我们使用time.sleep() 进行模拟等待。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值