Skip to main content
 首页 » 编程设计

Python:暂停功能但不是整个程序

2024年10月17日6mayingbao

我有两个函数,它们生成随机整数,并在给定的时间间隔内休眠。但是,我想独立休眠这两个函数,而 time.sleep() 暂停整个 Python 程序。

def fun1(): 
 interval1 = random.randint(2,800) 
 time.sleep(interval1) 
 # do other things 
 
def fun2(): 
 interval2 = random.randint(1, 999) 
 time.sleep(interval2) 
 # do other things, different than in fun2 

我如何休眠一个给定的函数,这样当 fun1 暂停时,fun2 仍然在做他们的事情,只要 time.sleep(interval2 ) 没有被调用?

请您参考如下方法:

试试这个:

from multiprocessing import Process 
 
def fun1(): 
    interval1 = random.randint(2,800) 
    time.sleep(interval1) 
    # do other things 
 
def fun2(): 
    interval2 = random.randint(1, 999) 
    time.sleep(interval2) 
    # do other things 
 
proc1 = Process(target=fun1) 
proc2 = Process(target=fun2) 
proc1.start() 
proc2.start() 
proc1.join() 
proc2.join() 

这将使用 multiprocessing 启动新的 Python 进程并行运行 fun1() 和 fun2()。 join() 调用将在主(父)进程中阻塞,直到 proc1 和 proc2 完成。

不幸的是,由于 Global Interpreter Lock , threading模块对性能帮助不大。但是,如果您的函数主要只是等待,Thread 可能是合适的。