Python thread learning (2)

Posted by saku on Sun, 05 Apr 2020 01:44:05 +0200

Create a Thread subclass MyThread

In order to make the subclass TyThread more general, the subclass is moved into a special module, and the callable getResult() method is added to return the obtained value

import threading
from time import sleep,ctime
class MyThread(threading.Thread):
    def __init__(self,func,args,name = ''):
        self.func = func#Incoming function
        self.args = args#Incoming parameter = name#Function name passed in
    def getResult(self):
        return self.res
    def run(self):
        #Special methods for passing initialization function parameters
        print('starting {0} at:{1}'.format(,ctime()))
        self.res = self.func(*self.args)
        print('{0} finished at: {1}'.format((,ctime())))

Comparison of single thread and multi thread execution

In this multithreaded application, three independent recursive functions will be executed successively in the way of single thread and Multithread

from myThread import MyThread
from time import ctime,sleep
#Fibonacci series
def fib(x):
    if x<2:return 1
    return (fib(x-2)+fib(x-1))
def fac(x):
    if x<2:return 1
    return (x*fac(x-1))
def sum(x):
    if x<2:return 1
    return (x+sum(x-1))
funcs = [fib,fac,sum]
def main():
    nfuncs = range(len(funcs))
    print('---------Single thread running--------------')
    for i in nfuncs:
        print('{0}Begin with: {1}'.format(funcs[i].__name__,ctime()))
        print('Run time:{0}'.format(funcs[i](n)))
    threads = []
    for i in nfuncs:
        #First parameter function name, second parameter function parameter, third parameter function name
        t = MyThread(funcs[i],(n,),funcs[i].__name__)
    for i in nfuncs:
    for i in nfuncs:
    print('End of all operation')
if __name__ == '__main__':

Operation result

The result shows

Method run() starts loading when the thread start() method is called. When the thread is created, the run() method does not start loading.