1. 程式人生 > >thread模組

thread模組

# -*- coding: UTF-8 -*-
import thread
import time

def loop0():
    print "start loop0 at :" , time.ctime()
    time.sleep(4)
    print "loop0 done at :", time.ctime()
    
def loop1():
    print "start loop1 at:", time.ctime()
    time.sleep(4)
    print "loop1 done at:", time.ctime()
    
def main():
    print "starting at :", time.ctime()
    thread.start_new_thread(loop0, ())
    thread.start_new_thread(loop1, ())
    time.sleep(6)
    print "all done at: ", time.ctime()
    
if __name__ == "__main__":
    main()


# -*- coding: UTF-8 -*-
import thread
import time

loops = [4, 2]

def loop(nloop, nesc, lock):
    print "start loop", nloop, "at:", time.ctime()
    time.sleep(nesc)
    print "loop", nloop, "done at:", time.ctime()
    lock.release()
    
def main():
    print "starting at ", time.ctime()
    locks = []
    nloops = range(len(loops))
    
    for i in nloops:
        lock = thread.allocate_lock()
        lock.acquire()
        locks.append(lock)
        
    for i in nloops:
        thread.start_new_thread(loop, (i, loops[i], locks[i]))
        
    for i in nloops:
        while locks[i].locked():
            pass
            
    print "all done at:", time.ctime()
    
if __name__ == "__main__":
    main()