In [2]:
import threading
from time import ctime, sleep
In [3]:
class 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.res
In [6]:
def i_o(x):
"""Mimic IO using sleep."""
sleep(x)
return x
In [9]:
def 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()))
In [8]:
main()
In [ ]: