0

So basically I'm writing a threaded python program, which uses 10 threads, stored in a variable called threads. There loop that starts the threads looks like this:

for x in xrange(threads):
     print "STARTING THREAD " + str(x)
     t = threading.Thread(target=worker)
     t.setDaemon(True)
     t.start()

The program executes normally, except for the fact that after it prints STARTING THREAD 9, it just exits without executing the worker function. The worker function looks like this.

def worker():
     try:
         while True:
             try:
                 ss = my_class()
                 ss.start()
                 time.sleep(0.009)
             except:
                 pass
     except:
          pass

The class has threading.Thread.__init__(self) in it's init method, and is declared like class my_class(threading.Thread)

I can't seem to figure out what's wrong, and nobody else seemed to have had this problem.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    It's because you made it a daemon thread with the `setDaemon()` call. See [this answer](http://stackoverflow.com/a/38805873/355230) of mine to another question for more information and links to the relevant documentation. – martineau Jan 27 '17 at 03:07
  • You explicitly set the threads as daemon threads, then wonder why they don't keep the program alive? Something tells me you're engaged in [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming), copying code snippets you don't understand and can't be bothered to understand, crossing your fingers and hoping they work. – ShadowRanger Jan 27 '17 at 03:15
  • @ShadowRanger: Yes, it seems that many of today budding programmers just want to be given some [boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_code) which they can then plop into their project with little thought or understanding of how it works or how well it fits in. – martineau Jan 27 '17 at 03:41
  • @ShadowRanger relax, I'm not just running around copying and pasting. I wanted to thread it but didn't quite know how to. Before I used the setDaemon flag, it would start one thread, and then hang because it had to run until the program was done, but because it couldn't start any other threads, the program couldn't run, and it wouldn't ever finish. When I used the setDaemon flag, it started the threads and didn't do anything after that, and I couldn't figure it out. If I'm a skid, I'm not a complete one. – LifeInKernelSpace Jan 27 '17 at 03:46
  • @user7423208: Huh? Daemon threads don't prevent the main thread from continuing, they have *only* one behavior, which is to allow the program to exit while they are running; a program exits when all non-daemon threads complete. Changing to daemon threads didn't cause your main thread to hang and block the launch of other threads, you made other changes and probably didn't understand them either. – ShadowRanger Jan 27 '17 at 12:32

0 Answers0