当前位置:编程学习 > 网站相关 >>

python多线程

1.创建threading.Thread的子类来包装一个线程对象
#encoding:utf8
 
import threading
import time
 
class timer(threading.Thread):
    def __init__(self,num,interval):
        threading.Thread.__init__(self)
        #设置产生线程的个数
        self.thread_num = num
        #产生线程的相隔时间
        self.interval = interval
        self.thread_stop = False
 
    def run(self):
        while not self.thread_stop:
            print 'Thread Object(%d),Time:%s\n'%(self.thread_num,time.ctime())
            time.sleep(self.interval)
 
    def stop(self):
        self.thread_stop = True
 
 
def test():
    thread1 = timer(1,1)
    thread2 = timer(2,2)
    thread1.start()
    thread2.start()
    time.sleep(10)
    thread1.stop()
    thread2.stop()
    return
 
if __name__ == '__main__':
    test()
    
threading.Thread类的使用:
1).在自己的线程类的__init__里调用threading.Thread.__init__(self, name = threadname)
Threadname为线程的名字
2). run(),通常需要重写,编写代码实现做需要的功能。
3).getName(),获得线程对象名称
4).setName(),设置线程对象名称
5).start(),启动线程
6).jion([timeout]),等待另一线程结束后再运行。
7).setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
8).isDaemon(),判断线程是否随主线程一起结束。
9).isAlive(),检查线程是否在运行中。
    此外threading模块本身也提供了很多方法和其他的类,可以帮助我们更好的使用和管理线程。可以参看http://www.python.org/doc/2.5.2/lib/module-threading.html。
2.简单的同步
#encoding:utf8
 
import threading
 
mylock = threading.RLock()
num = 0
 
class myThread(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.t_name = name
 
    def run(self):
        global num
        while True:
            mylock.acquire()
            print '\nThread(%s) locked,Number:%d'%(self.t_name,num)
            if num >= 4:
                mylock.release()
                print '\nThread(%s) released,Number:%d'%(self.t_name,num)
                break
            num += 1
            print '\nThread(%s) released,Number:%d'%(self.t_name,num)
            mylock.release()
 
 
def test():
    thread1 = myThread('A')
    thread2 = myThread('B')
    thread1.start()
    thread2.start()
 
if __name__ == '__main__':
    test()
   Python的threading module是在建立在thread module基础之上的一个module,在threading module中,暴露了许多thread module中的属性。在thread module中,python提供了用户级的线程同步工具“Lock”对象。而在threading module中,python又提供了Lock对象的变种: RLock对象。RLock对象内部维护着一个Lock对象,它是一种可重入的对象。对于Lock对象而言,如果一个线程连续两次进行acquire操作,那么由于第一次acquire之后没有release,第二次acquire将挂起线程。这会导致Lock对象永远不会release,使得线程死锁。RLock对象允许一个线程多次对其进行acquire操作,因为在其内部通过一个counter变量维护着线程acquire的次数。而且每一次的acquire操作必须有一个release操作与之对应,在所有的release操作完成之后,别的线程才能申请该RLock对象。修改共享数据的代码成为“临界区”。必须将所有“临界区”都封闭在同一个锁对象的acquire和release之间。
 
 
 
 
 
 
 
 
 
 
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,