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

时间:2016-07-25 10:42:04

标签: python multithreading python-2.7 sleep

我有两个函数,它生成随机整数,并在给定的时间间隔内休眠。但是,我想独立地睡眠这两个函数,而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)仍在做他们的事情?

2 个答案:

答案 0 :(得分:1)

简单地这样做:

from threading import Thread
thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()

这将启动两个独立于主线程的线程,分别调用fun1fun2

示例:

from threading import Thread
import random
import time

starttime = time.time()

def fun1():
    interval1 = random.randint(1,5)
    time.sleep(interval1)
    print "%d sec: Fun1" % (time.time() - starttime)

def fun2():
    interval2 = random.randint(1,5)
    time.sleep(interval2)
    print "%d sec: Fun2" % (time.time() - starttime)

thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()

print "Still doing things!"

输出:

Still doing things!
2 sec: Fun2
4 sec: Fun1

正如您所看到的,函数已运行但代码仍然继续在线程之后执行print语句。

答案 1 :(得分:1)

试试这个:

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()调用将在主(父)流程中阻止,直到proc1proc2完成。

不幸的是,由于Global Interpreter Lockthreading模块对性能影响不大。但是如果你的功能大多只是等待,Thread可能是合适的。