我想创建将向数组中添加内容的线程,但是,如果它们在不到2秒钟内没有这样做,我想终止它们。
这是一个概念证明,因此代码很简单。我希望线程每秒钟将其添加到列表中,因此线程在0、1、2、3和4秒后运行。想法是不要让线程3和4运行。
import threading, time
myList = []
def foo(value):
global myList
time.sleep(value)
print("Value: {}".format(value))
myList.append(value)
threads = []
for i in range(5):
th = threading.Thread(target=foo, args=(i,))
threads.append(th)
for th in threads:
th.start()
现在我该怎么做?我尝试使用其他一些逻辑,例如使用
th.join(timeout)
但这似乎不起作用。
正如我在评论中所说,您不能真正(外部)“杀死”线程。但是,他们可以通过返回或提出例外情况来“自杀”。
下面是当线程的执行时间超过给定时间时执行后者的示例。请注意,这与进行join(timeout)
调用不同,后者仅在线程结束或经过指定的时间后才阻塞。因此value
,无论线程是否在调用join()
超时之前完成,都将打印和附加到列表。
我sys.settrace()
从标题为“杀死线程的不同方法”的教程中获得了使用的基本思想,尽管我的实现略有不同。还要注意,这种方法可能会引入大量开销。
import sys
import threading
import time
class TimelimitedThread(threading.Thread):
def __init__(self, *args, time_limit, **kwargs):
self.time_limit = time_limit
self._run_backup = self.run # Save superclass run() method.
self.run = self._run # Change it to custom version.
super().__init__(*args, **kwargs)
def _run(self):
self.start_time = time.time()
sys.settrace(self.globaltrace)
self._run_backup() # Call superclass run().
self.run = self._run_backup # Restore original.
def globaltrace(self, frame, event, arg):
return self.localtrace if event == 'call' else None
def localtrace(self, frame, event, arg):
if(event == 'line' and
time.time()-self.start_time > self.time_limit): # Over time?
raise SystemExit() # Terminate thread.
return self.localtrace
THREAD_TIME_LIMIT = 2.1 # Secs
threads = []
my_list = []
def foo(value):
global my_list
time.sleep(value)
print("Value: {}".format(value))
my_list.append(value)
for i in range(5):
th = TimelimitedThread(target=foo, args=(i,), time_limit=THREAD_TIME_LIMIT)
threads.append(th)
for th in threads:
th.start()
for th in threads:
th.join()
print('\nResults:')
print('my_list:', my_list)
输出:
Value: 0
Value: 1
Value: 2
Results:
my_list: [0, 1, 2]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句