progloverfan
progloverfan

Reputation: 165

ReCreating threads in python

I'm using the following template to recreate threads that I need to run into infinity. I want to know if this template is scalable in terms of memory. Are threaded destroyed properly?

import threading
import time

class aLazyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        time.sleep(10)
        print "I don not want to work :("

class aWorkerThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        time.sleep(1)
        print "I want to work!!!!!!!"

threadA = aLazyThread()
threadA.start()
threadB = aWorkerThread()
threadB.start()

while True:

    if not (threadA.isAlive()):
        threadA = aLazyThread()
        threadA.start()

    if not (threadB.isAlive()):
        threadB = aWorkerThread()
        threadB.start()

The thing that bother me is the following picture taking in eclipse which show debug info, and It seems that thread are stacking it.

Thread counts

Upvotes: 1

Views: 238

Answers (1)

CristiFati
CristiFati

Reputation: 41147

  1. I see nothing wrong with the image. There's the main thread and the 2 threads that you created (according to the code, 3 threads are supposed to be running at any time)

  2. Like any other Python objects, threads are garbage collected when they're not used; e.g. in your main while cycle, when you instantiate the class (let's say aLazyThread), the old threadA value is destroyed (maybe not exactly at that point, but shortly after)

  3. The main while cycle, could also use a sleep (e.g. time.sleep(1)), otherwise it will consume the processor, uselessly checking if the other threads are running.

Upvotes: 1

Related Questions