def main(argv):
call otherdef(1,2,3) in a new thread
sleep for 10 minutes
kill the otherdef process
def otherdef(num1, num2, num3):
while(True):
print num1
import time
import threading
def otherdef(num1, num2, num3):
#Inside of otherdef we use an event to loop on,
#we do this so we can have a convent way to stop the process.
stopped = threading.Event()
#set a timer, after 10 seconds.. kill this loop
threading.Timer(10, stopped.set).start()
#while the event has not been triggered, do something useless
while(not stopped.is_set()):
print 'doing ', num1, num2, num3
stopped.wait(1)
print 'otherdef exiting'
print 'Running'
#create a thread, when I call start call the target and pass args
p = threading.Thread(target=otherdef, args=(1,2,3))
p.start()
#wait for the threadto finish
p.join(11)
print 'Done'
这里有一个解决方案,但它并不像你所要求的那样,因为杀死一个线程很复杂。最好让线程自行终止,所有线程默认为daemonic=False(除非它的父线程是daemonic),因此当主线程死亡时,您的线程将继续存在。设置为true,它将与主线程一起消亡。在
基本上,您所要做的就是启动一个
Thread
并给它一个运行的方法。您需要能够传递参数,这样您就可以看到我传递了一个args=
参数和要传递给目标方法的值。在仍然不清楚您是想要一个进程还是一个线程,但是如果您想要一个},那么其他的一切都保持不变。在
Process
导入多处理并将threading.Thread(
切换到{相关问题 更多 >
编程相关推荐