Skip to content

Instantly share code, notes, and snippets.

@raviolliii
Last active February 17, 2024 13:37
Show Gist options
  • Save raviolliii/94e9e16ef74f3c4f0886c6eb1fdfa157 to your computer and use it in GitHub Desktop.
Save raviolliii/94e9e16ef74f3c4f0886c6eb1fdfa157 to your computer and use it in GitHub Desktop.
Multithreading Decorator in python
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
@Rusca8
Copy link

Rusca8 commented Feb 17, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment