我想在套接字事件中停止/杀死N个线程。我目前的应用程序结构找不到任何方法。
这里是启动线程的代码:
for i in range(news_viewers):
t = threading.Thread(target=bot, args=(i + 1,))
t.daemon = True
t.name = "Viewer"
t.start()
当我收到事件时,我想杀死/停止列表中名为Viewer的N个线程:
for i in range(number_of_threads_to_kill):
#number_of_threads_to_kill is received by sockerIO
for t in threading.enumerate():
if 'Viewer' in t.getName():
#I NEED TO CLOSE N THREAD HERE
print('CLOSE THIS THREAD')
我找不到解决方法,我尝试了很多事情,但都无济于事。
threading.enumerate()返回此:
.., <Thread(Viewer, started daemon 41868)>, <Thread(Viewer, started daemon 53872)>, <Thread(Viewer, started daemon 54748)>, <Thread(Viewer, started daemon 50028)>,...
有人可以帮助我进行设置吗?
我终于找到了一种关闭线程的方法。
启动线程时,我将线程的ID添加到threads_ids数组中:
global stop_ids, threads_ids
for i in range(news_viewers):
tid = random.randint(1, 1000)
threads_ids.append(tid)
t = threading.Thread(target=bot, args=(tid,))
t.daemon = True
t.name = "Viewer"
t.start()
[当我想关闭线程时,我在stop_ids数组上添加了第一个ID:
global stop_ids, threads_ids
n = threads_ids[:number_of_thread_to_close]
stop_ids = stop_ids + n
在我的机器人功能上,我每N秒检查一次当前线程的id是否在stop_ids上:
def bot(id):
global stop_ids
...
q = True
while q:
if id in stop_ids:
stop_ids.remove(id)
driver.quit()
q = False
break
...