Last active
June 16, 2023 14:04
-
-
Save jijosg/80d480ae01b19c65fe0fa25bb507d5b3 to your computer and use it in GitHub Desktop.
Multithreading using Python
This file contains hidden or 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
#!/usr/bin/env python3 | |
import concurrent.futures as futures | |
import random | |
import threading | |
from concurrent.futures.thread import ThreadPoolExecutor | |
l = [[1, 2, 3], [2, 3, 4], [3, 5, 7], [3, 5, 8], [3, 5, 9]] | |
def foo(bar): | |
val = threading.get_native_id() * random.randint(1, 100) | |
print("hello {} {}".format(val, bar)) | |
return val, bar | |
def task2(thread, list): | |
print(f"You are inside {thread} ") | |
for i in list: | |
print(i) | |
return thread | |
def task3(thread): | |
print(f"Got {thread}") | |
if __name__ == "__main__": | |
with futures.thread.ThreadPoolExecutor(5) as executor: | |
futures1 = [executor.submit(foo, sub_list) for sub_list in l] | |
futures2 = list() | |
futures3 = list() | |
for future1 in futures.as_completed(futures1): | |
# get the result | |
thread_no, list_values = future1.result() | |
# check if we should trigger a follow-up task | |
future2 = executor.submit(task2, thread_no, list_values) | |
futures2.append(future2) | |
for future2 in futures.as_completed(futures2): | |
thread_no_2 = future2.result() | |
future3 = executor.submit(task3, thread_no_2) | |
futures3.append(future3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment