Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:暂停函数,但不是整个程序_Python_Multithreading_Python 2.7_Sleep - Fatal编程技术网

Python:暂停函数,但不是整个程序

Python:暂停函数,但不是整个程序,python,multithreading,python-2.7,sleep,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 thing

我有两个函数,它们生成随机整数,并在给定的时间间隔内休眠。但是,我想独立地休眠这两个函数,而
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
只要
时间长,就仍然在执行它们的操作。不调用sleep(interval2)

from threading import Thread
thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()
这将启动两个独立于主线程的线程,分别调用
fun1
fun2

例如:

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语句。

尝试以下操作:

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()
这将启动新的Python进程,使用并行运行
fun1()
fun2()
join()
调用将在主(父)进程中阻塞,直到
proc1
proc2
完成


不幸的是,由于性能问题,该模块对性能没有多大帮助。但是,如果您的函数大部分只是在等待,
Thread
s是合适的。

您需要返回值吗?
fun1()
fun2()
听起来像是在要求多线程或异步编程。查看Python异步IO(Python 3.4+)。Python 2或Python 3?@Will,不,它们不需要返回value@Ziva在这种情况下,他们会完成工作吗?这取决于他的工作量。如果我们只是在睡觉,那绝对是,但可能需要一个过程的是
#do stuff
部分:)无论如何都要被投票否决;我回答了关于多重处理的问题,威尔确实同意。根据用法,两个答案都是有效的。