Created
February 25, 2019 14:10
-
-
Save mijdavis2/96c53684e587da74c745d334e1fe7362 to your computer and use it in GitHub Desktop.
Python multithreading made easy
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
""" | |
Note: Found somewhere on Stack Overflow but was unable to find again. | |
If found, please comment and I will update this gist with the source. | |
""" | |
def threadwrap(func, args, kwargs): | |
class res(object): | |
result = None | |
def inner(*args, **kwargs): | |
res.result = func(*args, **kwargs) | |
import threading | |
t = threading.Thread(target=inner, args=args, kwargs=kwargs) | |
res.thread = t | |
return res | |
# Usage | |
def function_a(): | |
# do something | |
pass | |
def function_b(my_arg): | |
# do something | |
print(my_arg) | |
def function_c(my_arg, my_kwarg='someplace'): | |
# do something | |
print("{} {}".format(my_arg, my_kwarg)) | |
if __name__ == "__main_": | |
a = threadwrap(function_a, [], {}) | |
b = threadwrap(function_b, ['Function b arg.'], {}) | |
c = threadwrap(function_c, ['Hello,'], {'my_kwarg': 'World!'}) | |
a.thread.start() | |
b.thread.start() | |
c.thread.start() | |
a.thread.join() | |
b.thread.join() | |
c.thread.join() | |
# To use with class methods, use threadwrap in a method in the same class. | |
# Combine with timeit to see how long each thread runs! https://gist.github.com/mijdavis2/f66bec85fdb33d2b46a96c2cdc7f7688 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment