Search code examples
pythonpython-multithreading

Why I can't get the output of "I get the source"


I am trying to build a server to handle long time task job, so I made a global variable tasks so that request can easily returned by only put task info into tasks, and I using threading to build a function to handle the long time task job.
however I can't receive the tasks change in test(), why had this happen?

import time
import threading
from collections import OrderedDict

tasks = OrderedDict()


def request():
    # network gross
    # ...
    global tasks
    tasks['zdx'] = 2


def test():
    print('test runing')
    while True:
        if tasks:
            task = tasks.popitem()
            print('I get the source!')
            # very long time resolve task
        time.sleep(1)


def init():
    threading.Thread(target=test, daemon=True).start()


init()
time.sleep(3)
request()


Solution

  • You may want to review what daemon=True does for a thread. Effectively, right as you called request() to put an entry into tasks, your program exits and the thread gets terminated (as it has daemon=True set) before it finished sleeping and never got a chance to find out if anything is in tasks, thus it never got a chance to run. To correct for this, putting in a time.sleep(3) after request() at the end will ensure more than enough time for the loop in the thread to finish sleeping and process the check.