1

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 is 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 return not enough?)

i'm sure the old threads work is done as i'm printing the results , but i'm not sure why they still active afterward , any direct way to kill a thread after it finish his work ?

  • There are only 20 threads right? where are you creating other 440? – Vikas Madhusudana Aug 08 '16 at 11:30
  • i'm calling `main_threader` from another file normally without using threads with a for loop , as i know you can pass the main_threader(args) instruction without finishing the previous threads ? – Deborah Thomas Aug 08 '16 at 11:38
  • _"Daemon threads are abruptly stopped at shutdown"_. This means they remain running until your program stops, which is why you have such a high number of threads running even though they seem to have finished their work. – DocZerø Aug 08 '16 at 11:47
  • Ok , how do i kill the finished ones , without stopping the program , or do i have to change `t.daemon = True` to `False` ? – Deborah Thomas Aug 08 '16 at 11:49
  • You cannot _kill_ a thread. See [this](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) SO question how to use events in order to stop threads. – DocZerø Aug 08 '16 at 11:50
  • that seems way advance than my level right now , there is no simple approach to do the same ? – Deborah Thomas Aug 08 '16 at 11:58
  • @DeborahThomas, if thread has daemon flag it will run until the main process exits. So if you set that flag to False, when thread finish it will join to the main process. Also remember that ["The entire Python program exits when no alive non-daemon threads are left..."](https://docs.python.org/2/library/threading.html#threading.Thread.daemon) – Tomás Gonzalez Dowling Aug 08 '16 at 12:24

0 Answers0