🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## thread模块 较底层次线程模块 使用thread模块开启的线程,会随主线程`一起结束`;为了让子线程能够执行完任务,所以可以让主线程睡眠或者给主线程加锁,等待子线程结束后再释放锁。 ```python #!/usr/bin/env python #coding: utf-8 #python2 """为了不让主进程执行完就退出,给主线程加锁,当子线程执行结束后,释放主线程的锁 存在的问题: 当两个线程执行次数不一致时,先结束的线程即会释放主线程的锁,导致未执行完的线程被迫退出 """ import thread import time def processor(thread_name, times): for i in range(times): print i, thread_name time.sleep(0.001) # for循环结束,释放锁 lock.release() lock = thread.allocate_lock() lock.acquire() thread.start_new_thread(processor, ('image', 5)) thread.start_new_thread(processor, ('sound', 3)) while lock.locked(): pass ``` ### 当线程间的执行需要一定次序时,则需要给子线程也加锁。 当主线程,hello线程和world线程,执行到需要获取锁的时候,如果获取不到锁,则阻塞在那里;world线程在获取锁 world_thread_lock的时候阻塞了,当hello线程释放了 锁world_thread_lock,输出了‘world’;此时hello线程也在获取锁过程中阻塞了,所以当world线程释放了hello_thread_lock,输出了hello,这样交替释放彼此的锁,实现了顺序运行 ![](http://i2.muimg.com/567571/5ef5968d58a2be35.png) ```python #!/usr/bin/env python #coding: utf-8 #python2 import time import thread def hello(): for i in xrange(5): hello_thread_lock.acquire() print 'hello', time.time(), world_thread_lock.release() def world(): for i in xrange(5): world_thread_lock.acquire() print 'world', time.time() hello_thread_lock.release() time.sleep(1) # 释放主进程的锁 main_thread_lock.release() main_thread_lock = thread.allocate_lock() main_thread_lock.acquire() hello_thread_lock = thread.allocate_lock() world_thread_lock = thread.allocate_lock() world_thread_lock.acquire() thread.start_new_thread(hello, ()) thread.start_new_thread(world, ()) while main_thread_lock.locked(): pass ``` ```python #!/usr/bin/env python # coding: utf8 import thread from time import sleep, ctime loops = [4, 2] def loop(nloop, nsec, lock): print 'start loop', nloop, 'at:', ctime() sleep(nsec) print 'loop', nloop, 'done at:', ctime() lock.release() def main(): print 'starting threads...' locks = [] loops_len = range(len(loops)) # 生成锁列表 for i in loops_len: lock = thread.allocate_lock() lock.acquire() locks.append(lock) # 开启进程 for i in loops_len: thread.start_new_thread(loop, (i, loops[i], locks[i])) # 等待所有的lock都释放 for i in loops_len: while locks[i].locked(): pass print 'all DONE at:', ctime() if __name__ == '__main__': main() ```