如何在python中杀死旧线程

时间:2016-08-07 16:29:11

标签: python multithreading

我的多线程脚本引发了这个错误:

thread.error : can't start new thread

当它达到460个线程时:

threading.active_count() = 460

我认为旧线程保持堆叠,因为脚本没有杀死它们。这是我的代码:

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()

如何在作业完成后杀死旧线程? (函数返回不够吗?)

1 个答案:

答案 0 :(得分:1)

Python threading API没有任何杀死线程的功能(不像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!"