Last active
April 18, 2018 09:10
-
-
Save onfe/2ac9d20a1318139cfb571489b57faf3b to your computer and use it in GitHub Desktop.
An example of multi-threading in python using the threading module
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 threading | |
import time | |
def calc_square(numbers): | |
print('calc square numbers') | |
for n in numbers: | |
time.sleep(0.2) | |
print('square: ', n*n) | |
def calc_cube(numbers): | |
print('calc cube numbers') | |
for n in numbers: | |
time.sleep(0.2) | |
print('cube: ', n*n*n) | |
t = time.time() | |
a = range(0,5) | |
t1 = threading.Thread(target=calc_square, args=(a,)) | |
t2 = threading.Thread(target=calc_cube, args=(a,)) | |
t1.start() | |
time.sleep(0.1) | |
t2.start() | |
# wait for tasks to complete | |
t1.join() | |
t2.join() | |
print('time: ' + str(time.time() - t)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment