简体   繁体   中英

How to kill old threads in python

My multi-threading script raising this error:

thread.error : can't start new thread

when it reached 460 threads:

threading.active_count() = 460

I assume the old threads keeps stack up, since the script didn't kill them. This my code:

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

How do I kill the old threads when their job is done? (Is the function returning not enough?)

Python threading API doesn't have any function to kill a thread (nothing like threading.kill(PID) ).

That said, you should code some thread-stopping algorithm yourself. For example, your thread should somehow decide that is should terminate (eg check some global variable or check whether some signal has been sent) and simply return .


For example:

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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM