Skip to content

Instantly share code, notes, and snippets.

@onfe
Last active April 18, 2018 09:10
Show Gist options
  • Save onfe/2ac9d20a1318139cfb571489b57faf3b to your computer and use it in GitHub Desktop.
Save onfe/2ac9d20a1318139cfb571489b57faf3b to your computer and use it in GitHub Desktop.
An example of multi-threading in python using the threading module
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