Tak*_*kun 43 python multithreading
我想在一段时间后终止一些线程.这些线程将运行无限循环,在此期间它们可以随机停留大量时间.线程的持续时间不能超过持续时间变量设置的时间.如何在持续时间设置的长度之后,线程停止.
def main():
t1 = threading.Thread(target=thread1, args=1)
t2 = threading.Thread(target=thread2, args=2)
time.sleep(duration)
#the threads must be terminated after this sleep
Run Code Online (Sandbox Code Playgroud)
Nix*_*Nix 104
如果 您没有阻止,这将有效.
如果您正在计划睡眠,那么您必须使用该事件来进行睡眠.如果你利用这个事件来睡觉,如果有人告诉你在"睡觉"时停下来,它就会醒来.如果你使用time.sleep()你的线程只会在它醒来后停止.
import threading
import time
duration = 2
def main():
t1_stop = threading.Event()
t1 = threading.Thread(target=thread1, args=(1, t1_stop))
t2_stop = threading.Event()
t2 = threading.Thread(target=thread2, args=(2, t2_stop))
time.sleep(duration)
# stops thread t2
t2_stop.set()
def thread1(arg1, stop_event):
while not stop_event.is_set():
stop_event.wait(timeout=5)
def thread2(arg1, stop_event):
while not stop_event.is_set():
stop_event.wait(timeout=5)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105355 次 |
| 最近记录: |