Last active
February 17, 2024 13:37
-
-
Save raviolliii/94e9e16ef74f3c4f0886c6eb1fdfa157 to your computer and use it in GitHub Desktop.
Multithreading Decorator in 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
from threading import Thread | |
def threaded(func): | |
""" | |
Decorator that multithreads the target function | |
with the given parameters. Returns the thread | |
created for the function | |
""" | |
def wrapper(*args, **kwargs): | |
thread = Thread(target=func, args=args) | |
thread.start() | |
return thread | |
return wrapper | |
# Usage | |
# just add the threaded decorator above the function | |
# you want to multithread | |
@threaded | |
def some_func(results): | |
value = 'some_compute_heavy_value' | |
results.append(value) | |
@threaded | |
def other_func(results): | |
value = 'some_other_compute_heavy_value' | |
results.append(value) | |
@threaded | |
def third_func(results): | |
value = 'another_compute_heavy_value' | |
results.append(value) | |
threads = [] | |
results = [] | |
for _ in range(10): | |
threads.append(some_func(results)) | |
threads.append(other_func(results)) | |
threads.append(third_func(results)) | |
# wait for all threads to finish before moving on | |
for thread in threads: | |
thread.join() | |
results # populated list of api call results | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey. I guess you forgot the kwargs in the Thread call at line 11?
Feels like you got the **kwargs on line 10 but didn't use them in the end.