Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the Python module threading

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()
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
In [ ]:
 

Comments