# A Python example doing parallel sorting
# of the nodes of a version tree in topological order
# Number of worker threads: Two
import threading
import queue
from graphlib import TopologicalSorter
# The queues
versionQueue = queue.Queue()
doneQueue = queue.Queue()
# Worker thread function
def worker():
while True:
print("Id of worker thread:%d"%threading.get_native_id())
version = versionQueue.get()
versionQueue.task_done()
doneQueue.put(version)
# Creation of worker threads
workerThread1 = threading.Thread(target=worker, daemon=True)
workerThread2 = threading.Thread(target=worker, daemon=True)
# Start the workers
workerThread1.start()
workerThread2.start()
# Version tree as a DAG
versions = {"v2":{"v1"},
"v4":{"v2"},
"v3":{"v2"},
"v5":{"v3","v4"},
"v6":{"v5"},
}
topologicalSorter = TopologicalSorter(versions)
topologicalSorter.prepare()
# Loop till all the versions are printed
while topologicalSorter.is_active():
# Get a version that is ready
for version in topologicalSorter.get_ready():
versionQueue.put(version)
# Mark the completed version as done
vertex = doneQueue.get()
topologicalSorter.done(vertex)
print("From the main thread:%s"%vertex)
# Wait for the worker threads to complete
versionQueue.join()
print("Any version is yet to be done:%s"%topologicalSorter.is_active())
|