Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
https://
https://
import threading
from time import ctime, sleepclass MyThread(threading.Thread):
def __init__(self, func, args, name=""):
threading.Thread.__init__(self) # initialize Thread
self.func = func # the function for the thread to run
self.args = args # the arguments of func
self.name = name # name of thread
def run(self):
print("The thread %s started at %s" % (self.name, ctime()))
self.res = self.func(*self.args)
print("The thread %s ended at %s" % (self.name, ctime()))
def getResult(self):
return self.resdef i_o(x):
"""Mimic IO using sleep."""
sleep(x)
return xdef main():
fib_num = [[3], [2], [4]]
threads = []
for i, num in enumerate(fib_num):
threads.append(MyThread(i_o, num, i))
for item in threads:
item.start()
for item in threads:
item.join()
print("%s: %s" % (item.name, item.getResult()))main()The thread 0 started at Wed Dec 18 16:13:35 2019The thread 1 started at Wed Dec 18 16:13:35 2019
The thread 2 started at Wed Dec 18 16:13:35 2019
The thread 1 ended at Wed Dec 18 16:13:37 2019
The thread 0 ended at Wed Dec 18 16:13:38 2019
0: 3
1: 2
The thread 2 ended at Wed Dec 18 16:13:39 2019
2: 4