如何在python中杀死旧线程

2024-06-25 05:41:39 发布

您现在位置:Python中文网/ 问答频道 /正文

引发此错误的多线程脚本:

thread.error : can't start new thread

当达到460个螺纹时:

^{pr2}$

我想旧线程会一直堆积起来,因为脚本没有杀死它们。这是我的代码:

import threading
import Queue
import time
import os
import csv


def main(worker):
    #Do Work
    print worker
    return

def threader():
    while True:
        worker = q.get()
        main(worker)
        q.task_done()        

def main_threader(workers):
    global q
    global city
    q = Queue.Queue()
    for x in range(20):
        t = threading.Thread(target=threader)
        t.daemon = True
        print "\n\nthreading.active_count() = "  + str(threading.active_count()) + "\n\n"
        t.start()
    for worker in workers:
        q.put(worker)   
    q.join()

当旧线程的工作完成后,我如何杀死它们?(函数返回不够吗?)在


Tags: import脚本truequeuemaindef线程global
1条回答
网友
1楼 · 发布于 2024-06-25 05:41:39

PythonthreadingAPI没有任何杀死线程的函数(与threading.kill(PID)不同)。在

你自己说过应该停止一些代码。例如,您的线程应该以某种方式决定是否应该终止(例如,检查某个全局变量或检查是否发送了某些信号),然后简单地return。在


例如:

import threading


nthreads = 7
you_should_stop = [0 for _ in range(nthreads)]

def Athread(number):
    while True:
        if you_should_stop[number]: 
            print "Thread {} stopping...".format(number)
            return
        print "Running..."

for x in range(nthreads):
    threading.Thread(target = Athread, args = (x, )).start()

for x in range(nthreads):
    you_should_stop[x] = 1

print "\nStopped all threads!"

相关问题 更多 >