当我收到套接字事件时,我想停止/终止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.enumeter((返回this:
.., <Thread(Viewer, started daemon 41868)>, <Thread(Viewer, started daemon 53872)>, <Thread(Viewer, started daemon 54748)>, <Thread(Viewer, started daemon 50028)>,...
有人能帮我设置吗?
我终于找到了关闭线程的方法。
当我启动一个线程时,我会在threads_ids数组中添加线程的id:
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数组上添加N个第一个id:
global stop_ids, threads_ids
n = threads_ids[:number_of_thread_to_close]
stop_ids = stop_ids + n
在我的bot函数中,我每隔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
...