Python threading


1. 1つ目はthreadingを作成することですThread()のインスタンスで、関数を与えます.
import threading

from time import sleep, ctime

loops = [4, 2]

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)) #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 '
all Done at:', ctime() if __name__ == '__main__': main()

 
/-----------------------------------------------------------------------------------------------------------------------------------------------------
2.第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 '
start loop:', nloop, 'at:', ctime() sleep(nsec) print '
loop', 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()