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 = ''):
        threading.Thread.__init__(self)
        self.func = func#Incoming function
        self.args = args#Incoming parameter
        self.name = 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(self.name,ctime()))
        self.res = self.func(*self.args)
        print('{0} finished at: {1}'.format((self.name,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):
    sleep(0.005)
    if x<2:return 1
    return (fib(x-2)+fib(x-1))
#Factorial
def fac(x):
    sleep(0.1)
    if x<2:return 1
    return (x*fac(x-1))
#accumulation
def sum(x):
    sleep(0.1)
    if x<2:return 1
    return (x+sum(x-1))
funcs = [fib,fac,sum]
n=12
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)))
    print('---------Multithreading--------------')
    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__)
        threads.append(t)
    for i in nfuncs:
        threads[i].start()
    for i in nfuncs:
        threads[i].join()
        print(threads[i].getResult())
    print('End of all operation')
if __name__ == '__main__':
    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.