python多线程速度小技巧

普通的线程:

import threading

class MyThread(threading.Thread):
        def __init__(self, func):
                threading.Thread.__init__(self)
                self.func = func
        def run(self):
                apply(self.func)

def paxmac1():
        for i in range(50):
                print 'paxmac 1 : is :',i + 1

def paxmac2():
        for i in range(50):
                print 'paxmac 2 : is :',i + 1

funcs = [paxmac1,paxmac2]

def main():
        nfuncs = range(len(funcs))
        print '\n*** MULTIPLE THREADS ***'
        threads = []
        for i in nfuncs:
                t = MyThread(funcs[i])
                threads.append(t)
        for i in nfuncs:
                threads[i].start()
        for i in nfuncs:
                threads[i].join()
        print '*** ALL DONE ***'

if __name__ == '__main__':
        main()

 

MULTIPLE THREADS
paxmac 1 : 1
paxmac 1 : 2
…….
paxmac 1 : 50
paxmac 2 : is : 1
……..
paxmac 2 : is : 48
paxmac 2 : is : 49
paxmac 2 : is : 50
ALL DONE
速度挺快的 但是两个函数并不是同时执行的。

看下面的代码:

import threading

class MyThread(threading.Thread):
        def __init__(self, func):
                threading.Thread.__init__(self)
                self.func = func
        def run(self):
                apply(self.func)

class PaxMacMyThread(threading.Thread):
        def __init__(self, func, paxmac, i):
                threading.Thread.__init__(self)
                self.func = func
                self.paxmac = paxmac
                self.i = i
        def run(self):
                apply(self.func,(self.paxmac,self.i))

def pt(paxmac,i): print "paxmac",paxmac,": is :",i + 1 

def paxmac1():
        threads = []
        for i in range(50):
                t = PaxMacMyThread(pt,'1',i)
                threads.append(t)
        for i in range(50):
                threads[i].start()

def paxmac2():
        threads = []
        for i in range(50):
                t = PaxMacMyThread(pt,'2',i)
                threads.append(t)
        for i in range(50):
                threads[i].start()

funcs = [paxmac1,paxmac2]

def main():
        nfuncs = range(len(funcs))
        print '\n*** MULTIPLE THREADS ***'
        threads = []
        for i in nfuncs:
                t = MyThread(funcs[i])
                threads.append(t)
        for i in nfuncs:
                threads[i].start()
        for i in nfuncs:
                threads[i].join()
        print '*** ALL DONE ***'

if __name__ == '__main__':
        main()

 

输出:
MULTIPLE THREADS
paxmac 1 : is : 1
paxmac 2 : is : 1
…….
paxmac 1 : is : 20
paxmac 2 : is : 22
……..
ALL DONE

在线程中使用线程速度更快。