新手学Python 第十六篇 多线程(一)

全局解释器锁(GIL):保证多线程的执行
导入线程模块
>>> import thread
模块函数                           描述
start_new_thread(function,args,    创建一个新的线程,function为线程
kwargs=None)                       函数,kwargs表示参数,可选
allocate_lock()                    分配一个LockType类型的锁对象
exit()                             让线程退出


LockType类型锁对象方法


acquire(wait=None)                 尝试获取锁对象
locked()                           如果获取了锁对象True
release()                          解锁


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 at:',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:',ctime()


if __name__ == '__main__':
    main()


threading模块
Thread类对象的函数          描述
start()                   开始线程的执行
run()                     定义线程的功能的函数-->一般被子类重写
join(timeout=None)        程序挂起timeout秒,默认是直到程序结束
getName()                 返回线程的名字
setName()                 设置线程的名字
isAlive()                 布尔标志,表示这个线程是否还在运行中
isDaemon()                返回Daemon标志(标识主线程是否等待子线程)
setDaemon(daemonic)       设置Daemon标志            


使用上述函数示例:


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))


    for i in nloops:
        t = threading.Thread(target=loop,args=(i,loops[i]))
        threads.append(t)
    for i in nloops:
        threads[i].start()
    for i in nloops:
        threads[i].join()
if __name__== '__main__':
    main()


threading 模块中的其它函数
activeCount            当前活动的线程对象的数量
curentThread()         返回当前线程对象
enumerate()            返回当前活动线程的列表
settrace(func)         为所有线程设置一个跟踪函数
setprofile(func)       为所有线程设置一个profile函数
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值