1

I've already referred to this thread, but it seems to be outdated and there doesn't seem to be a clean explanation

Python daemon thread does not exit when parent thread exits

I'm running python 3.6 and trying to run the script from either IDLE or Spyder IDE.

Here is my code:

import threading
import time

total = 4

def creates_items():
    global total
    for i in range(10):
        time.sleep(2)
        print('added item')
        total += 1
    print('creation is done')


def creates_items_2():
    global total
    for i in range(7):
        time.sleep(1)
        print('added item')
        total += 1
    print('creation is done')


def limits_items():

    #print('finished sleeping')

    global total
    while True:
        if total > 5:

            print ('overload')
            total -= 3
            print('subtracted 3')
        else:
            time.sleep(1)
            print('waiting')


limitor = threading.Thread(target = limits_items, daemon = True)
creator1 = threading.Thread(target  = creates_items)
creator2 = threading.Thread(target = creates_items_2)


print(limitor.isDaemon())


creator1.start()
creator2.start()
limitor.start()


creator1.join()
creator2.join()

print('our ending value of total is' , total)

limitor thread doesn't seem to be ending despite being a daemon thread.

Is this a way to get this working from IDLE or Spyder?

Thanks.

Moondra
  • 4,399
  • 9
  • 46
  • 104
  • What makes you think it doesn't end? – cs95 Jun 29 '17 at 18:10
  • The print statement ('waiting') continues to be outputted after main thread ends. This is when using a Python console such as IDLE or Spyder (not the command prompt) – Moondra Jun 29 '17 at 18:21

1 Answers1

1

I had the same Problem and solved it by using multiprocessing instead of threading:

from multiprocessing import Process
import multiprocessing
from time import sleep

def daemon_thread():
    for _ in range(10):
        sleep(1)
        print("Daemon")

if __name__ == '__main__':
    multiprocessing.freeze_support()
    sub_process = Process(target = daemon_thread, daemon = True)
    sub_process.start()

    print("Exiting Main")

I haven't yet really understood why I need the call to freeze_support() but it makes the code work.