python_threading模块

时间:2015-05-14 20:46:23   收藏:0   阅读:129
#!/usr/bin/python
#coding=utf-8
import thread
from time import sleep,ctime
loops = [3,5]
#测试函数
def loop(nloop,nsec,lock):
    print ‘start loop‘,nloop,‘at‘,ctime()
    sleep(nsec)
    print ‘loop‘,nloop,‘done at‘,ctime()
    lock.release()
‘‘‘    
def main()
    print ‘start at‘.ctime()
    #locks=[]
‘‘‘
def main():
    print ‘start at:‘,ctime()
    locks = []
    nloops = range(len(loops))
    
    for i in nloops:
        #分配一个LockType的对象
        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 ‘,ctime()     
        
if __name__ == ‘__main__‘:
    main()

这个例子是一个python,线程的小例子

运行结果


wang@wang-virtual-machine:~/python/new$ python threading.py 

start at: Thu May 14 16:34:24 2015

start loop 1 at Thu May 14 16:34:24 2015

 start loop 0 at Thu May 14 16:34:24 2015

loop 0 done at Thu May 14 16:34:27 2015

loop 1 done at Thu May 14 16:34:29 2015

all Done at  Thu May 14 16:34:29 2015


本文出自 “linux-php-user” 博客,请务必保留此出处http://wangsheng219.blog.51cto.com/2147741/1651303

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!