Python threading

1.  第一种方式: 创建一个threading.Thread()的实例,给它一个函数。

import threading

from time import sleep, ctime

loops = [4, 2]

def loop(nloop, nsec):
   print '\nstart loop:', nloop, 'at:', ctime()
   sleep(nsec)
   print '\nloop', nloop, 'done at:', ctime()

def main():
   print '\nstarting at:\n', ctime()
   threads = []
   nloops = range(len(loops))

   #create the threads using threading
   for i in nloops:
   t = threading.Thread(target=loop, args=(i,loops[i]))
   threads.append(t)

   #start threads
   for i in nloops:
   threads[i].start()

   #wait for all
   for i in nloops:
   threads[i].join() #block
   
   print '\nall Done at:', ctime()

if __name__ == '__main__':
   main()

 

/-----------------------------------------------------------------------------------------------------------------------------------------------------

2. 第二种方式: 创建一个threading.Thread的实例,传给它一个可调用类对象,类中使用__call__()函数调用函数

import threading
from time import sleep, ctime

loops = [4,2]

class ThreadFunc(object):
   def __init__(self, func, args, name=''):
   self.name = name
   self.func = func
   self.args = args
   #when you create a new thread, Thread instance will invoke our ThreadFunc
   # instance, and at that time, it will call the function __call__()
   # Hence, we have a tuple arguments , so we use the self.res
   def __call__(self):
   self.res = self.func(*self.args) #invoke the func

def loop(nloop, nsec):
   print '\nstart loop:', nloop, 'at:', ctime()
   sleep(nsec)
   print '\nloop', nloop, 'done at:', ctime()

def main():
   print 'start at:', ctime()
   threads = [] #list
   nloops = range(len(loops))

   #crate all threads
   for i in nloops:
   t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]),loop.__name__))
   threads.append(t)

   #start all threads
   for i in nloops:
   threads[i].start()

   for i in nloops:
   threads[i].join()

   print 'all Done at:', ctime()

if __name__ == '__main__':
   main()

/-----------------------------------------------------------------------------------

3. 第三种方式: 派生一个threading.Thread出一个子类,创建这个子类的实例,使用run调用函数

import threading 
from time import sleep, ctime

loops = (4,2)

class MyThread(threading.Thread):
   def __init__(self, func, args, name=''):
   threading.Thread.__init__(self) #base class func
   self.name = name
   self.func = func
   self.args = args

   # in the other way, use __call__()
   def run(self):
   apply(self.func,self.args)

def loop(nloop, nsec):
   print 'start loop', nloop, 'at:', ctime()
   sleep(nsec)
   print 'loop', nloop, 'done at:', ctime()

def main():
   print 'starting at:',ctime()
   threads = []
   nloops = range(len(loops))

   for i in nloops:
   t = MyThread(loop, (i,loops[i]), loop.__name__)
   threads.append(t)

   for i in nloops:
   threads[i].start()

   for i in nloops:
   threads[i].join()

   print 'all Done at:', ctime()

if __name__ == '__main__':
   main()