Thread
import threading
from datetime import datetime
def show(n, s):
total = 0
from random import random
for i in range(n):
total += i
print('total={} start={} end={}'.format(total, str(s), str(datetime.now())))
if __name__ == "__main__":
max = 1000
jobs = []
for index in range(4):
s = datetime.now()
jobs.append(threading.Thread(target=show, args=[max, s]))
for index in range(4):
jobs[index].start()
for index in range(4):
jobs[index].join()
total=499500 start=2018-08-13 14:32:26.588980 end=2018-08-13 14:32:26.590985
total=499500 start=2018-08-13 14:32:26.588980 end=2018-08-13 14:32:26.591987
total=499500 start=2018-08-13 14:32:26.589481 end=2018-08-13 14:32:26.592990
total=499500 start=2018-08-13 14:32:26.589481 end=2018-08-13 14:32:26.593993
Multiprocessing
import multiprocessing
from datetime import datetime
def show(n, s):
total = 0
for i in range(n):
total += i
print('total={} start={} end={}'.format(total, str(s), str(datetime.now())))
if __name__ == "__main__":
max = 1000
jobs = []
for index in range(4):
s = datetime.now()
jobs.append(multiprocessing.Process(target=show, args=[max, s]))
for index in range(4):
jobs[index].start()
for index in range(4):
jobs[index].join()
output
total=499500 start=2018-08-13 14:24:28.087562 end=2018-08-13 14:24:28.803968
total=499500 start=2018-08-13 14:24:28.088063 end=2018-08-13 14:24:29.428128
total=499500 start=2018-08-13 14:24:28.088063 end=2018-08-13 14:24:30.018699
total=499500 start=2018-08-13 14:24:28.088063 end=2018-08-13 14:24:30.587712