python 多线程编程

python 提供了几个用于多线程编程的模块:
thread               基本的,低级别的线程模块
threading          高级别的线程和同步对象
Queue                供多线程使用的同步先进先出(FIFO)队列
mutex                互斥对象
SocketServer    具有线程控制的TCP和UDP管理器

避免使用thread模块,而使用threading模块:
1) 有更高级别的threading模块更为先进,对线程的支持更为完善,而且使用thread模块的属性有可能会threading出现冲突;
2) 低级别的thread模块的同步原语很少(实际只有一个),而threading模块则有很多。
3) 另外一个不推荐使用thread原因是,对于你的进程什么时候应该结束完全没有控制,当主线程结束时,所有的线程都会被强制结束掉,没有警告也不会有正常的清除工作,而threading模块能确保重要的子线程退出后进程才退出。
4)守护进程:thread不支持守护进程,当主线程退出时,所有的子线程不论它们是否还在工作,都会被强行退出,有时,我们并不期望这种行为。而threading模块支持守护线程,它们是这样工作的:守护线程一般是一个等待客户请求的服务器,如果没有客户提出请求,它就在那等着,如果你设定一个线程为守护线程,就表示你在说这个线程是不重要的,在进程退出的时候,不用等待这个线程退出。

thread类
函数                                              描述
start()                                           开始线程的执行
run()                                             定义线程的功能的函数(一般会被子类重写)
join(timeout=None)                      程序挂起,直到线程结束;如果给了timeout,最多阻塞timeout秒
getName()                                    返回线程的名字
setName()                                     设置线程的名字
isAlive()                                         布尔标示,表示这个线程是否还在运行中
isDaemon()                                    返回线程的daemon标志
setDaemon(dammonic)               把线程的daemon标志设置为daemonic(一定在调用start()函数前调用)

threading的 thread类是你主要的运行对象,它有很多thread模块里没有的函数, 用thread类,你可以有多种方法来创建线程,我们这里介绍三种比较类似的方法,实际使用中,可以选择任一种你喜欢的:

1. 创建一个thread的实例,传给它一个函数
'''''使用threading:创建一个Thread的实例,传给它一个函数'''   
import threading 
from time import ctime,sleep 
loops = [4,2,3] 
 
def loop(nloop,nsec): 
    print 'start loop',nloop,'at :',ctime() 
    sleep(nsec) 
    print 'loop',nloop,'done! at :',ctime() 
 
def main():    
    print 'MAIN thread start at :',ctime() 
    threads = [] 
    nloops = range(len(loops)) 
 
    for i in nloops:#create a instance for Thread class 
        t = threading.Thread(target=loop,  args=(i,loops[i]))  #创建Thread的实例, 并传递loop函数
        threads.append(t) 
 
    for i  in nloops:       #start threads 
        threads[i].start() 
 
    for i in nloops:  #wait for all threads finish 
        threads[i].join() 
         
    print 'all threads Done! at :',ctime() 
 
if __name__ == '__main__': 
    main()  
    
2. 创建一个thread的实例,传给它一个可调用的类对象
import threading 
from time import ctime,sleep 

loops = [4,2,3] 
class threadFunc(object): 
    """docstring for threadFunc""" 
    def __init__(self, func,  args,  name=''): 
        self.args = args 
        self.name = name 
        self.func = func 
     
    def __call__(self):   #__call__表示可调用的实例 
            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 'MAIN thread start at :',ctime() 
    threads = [] 
    nloops = range(len(loops)) 
 
    for i in nloops:#create a instance for Thread class 
        #创建Thread的实例, 并传递类对象
        t = threading.Thread(target=threadFunc(loop,  (i,loops[i]),   loop.__name__ ))  
        threads.append(t) 
 
    for i  in nloops:#start threads 
        threads[i].start() 
 
    for i in nloops:#wait for all threads finish 
        threads[i].join() 
         
    print 'all threads Done! at :',ctime() 
 
if __name__ == '__main__': 
    main() 
 
3. 从thread派生一个子类,创建一个这个子类的实例
import threading 
from time import ctime,sleep 
 
loops = [4,2,3] 
 
class MyThread(threading.Thread):    # 创建一个派生类
    """docstring for MyThread""" 
    def __init__(self, func,arg,name=''): 
        super(MyThread, self).__init__() 
        self.arg = arg 
        self.func = func 
        self.name = name 
         
    def run(self): 
            apply(self.func,self.arg)    
 
def loop(nloop,nsec): 
    print 'start loop',nloop,'at :',ctime() 
    sleep(nsec) 
    print 'loop',nloop,'done! at :',ctime() 
 
 
def main(): 
    print 'MAIN thread start at :',ctime() 
    threads = [] 
    nloops = range(len(loops)) 
 
    for i in nloops  :  #create a instance for Thread class 
        t = MyThread(loop,  (i,loops[i])) 
        threads.append(t) 
 
    for i  in nloops:#start threads 
        threads[i].start() 
 
    for i in nloops:#wait for all threads finish 
        threads[i].join() 
         
    print 'all threads Done! at :',ctime() 
 
if __name__ == '__main__': 
    main()


转载于:https://my.oschina.net/mingfu/blog/527609

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值