ThreadPool
is a simple tool for a common task. If you want to manage the queue yourself to get DFS behavior; you could implement the necessary functions in the upper threading
and queue
modules directly.
To prevent scheduling the next root task until all tasks generated by the current task are completed (DFS order), you can use Queue.join()
:
#!/usr/bin/env python3 import queue import random import threading import time def worker(q, multiplicity=5, maxlevel=3, lock=threading.Lock()): for task in iter(q.get, None):
Sample code is derived from the example in the queue
module documentation .
A task at each level spawns multiplicity
direct child tasks that spawn their own sub-tasks until maxlevel
.
None
used to alert workers that they should stop working. t.join()
used to wait until threads become elegant. If the main thread is interrupted for any reason, then the daemon threads will be killed if there are no other threads not associated with daemons (you might want to provide a SIGINT hanlder to signal workers to gracefully exit Ctrl+C
instead of just die).
queue.LifoQueue()
used to get the "Last In First Out" order (it is approximate due to multiple threads).
maxsize
not set, because otherwise the workers may get into a dead end - you still have to set a task. worker_count
background threads run independently of the task queue.
source share