Created
December 14, 2022 12:04
-
-
Save kkpattern/28ef63b3d1054a6bcd66d9f65e009dc3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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