Skip to content

Instantly share code, notes, and snippets.

@kkpattern
Created December 14, 2022 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkpattern/28ef63b3d1054a6bcd66d9f65e009dc3 to your computer and use it in GitHub Desktop.
Save kkpattern/28ef63b3d1054a6bcd66d9f65e009dc3 to your computer and use it in GitHub Desktop.
import concurrent.futures
import time
class Tree:
def __init__(self, left=None, right=None):
self.left = left
self.right = right
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
def count_tree(future, tree):
time.sleep(1)
left_counted = right_counted = False
count = 1
def _set_result():
if left_counted and right_counted:
future.set_result(count)
if tree.left:
def _left_result(f):
nonlocal count, left_counted
left_counted = True
count += f.result()
_set_result()
f = executor.submit_f(count_tree, tree.left)
f.add_done_callback(_left_result)
else:
left_counted = True
if tree.right:
right = None
def _right_result(f):
nonlocal count, right_counted
right_counted = True
count += f.result()
_set_result()
f = executor.submit_f(count_tree, tree.right)
f.add_done_callback(_right_result)
else:
right_counted = True
_set_result()
t = Tree(left=Tree(left=Tree(left=Tree()), right=Tree()))
f = executor.submit_f(count_tree, t)
print(f.result())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment