1

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()

Cam
  • 14,930
  • 16
  • 77
  • 128
周剑伟
  • 13
  • 3
  • Try putting a `time.sleep(3)` after `request()`, as the program terminated before the daemonised thread has a chance to respond to the task. – metatoaster Jun 21 '22 at 03:49
  • You need to pass `tasks` as an argument to `test`, otherwise `tasks` (inside of `test`) keeps the value it had when `test` was defined. – Henry Woody Jun 21 '22 at 03:51
  • @HenryWoody nope, `tasks` can be accessed from `test()` as is because it didn't define a local `tasks` variable and it already exists on the global scope. – metatoaster Jun 21 '22 at 03:53
  • @metatoaster yeah you're right, I've forgotten the wild rules of Python. – Henry Woody Jun 21 '22 at 04:25

1 Answers1

1

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.

metatoaster
  • 17,419
  • 5
  • 55
  • 66