百度空间 | 百度首页 
 
查看文章
 
Python学习笔记系列--多线程
2008/01/17 20:37

(一)在Python中创建一个线程对象

类继承threading.Thread

在__init__里调用threading.Thread.__init__(self, name = threadname)

threadname为线程名字,这样就实现了一个空线程

重写run()方法:需要做的事情

getName() 获得线程对象名称

setName() 设置线程对象名称

start() 启动线程

线程的状态:

runable 运行

sleeping 等待

dead 销毁(run方法执行完成或执行时抛出异常)

jion(t) 等待另某一线程结束后再运行

参数t为可选,单位为秒,为等待时间

setDaemon(bool) 子线程是否随主线程一起结束,必须在start()之前调用,默认为False

True 子线程随主线程一起结束

False 子线程不随主线程一起结束

currentThread() 获取当前正在运行的线程的引用

enumerate() 获取当前所有活动对象的一个列表

activeCount() 获取一个线程对象的状态

1 表示runnable

例子一:

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name = threadname)
    def run(self):
        for i in range(10):
            print self.getName(), i
            time.sleep(1)

if __name__ == '__main__':
    t1 = MyThread('MyThread')
    print t1.getName(), t1.isDaemon() # False
    #t1.setDaemon(True)
    #print t1.getName(), t1.isDaemon() # True

    t1.start()
    print 'Main thread exit'
    print 'CurrentThread', threading.currentThread()
    print 'Enumrate', threading.enumerate()
    print 'ActiveCount', threading.activeCount()
    print 'IsAlive', t1.isAlive()
    ###############################################################################
    # Console:
    # MyThread False
    # MyThread 0
    # Main thread exit
    # CurrentThread <_MainThread(MainThread, started)>
    # Enumrate [<MyThread(MyThread, started)>, <_MainThread(MainThread, started)>]
    # ActiveCount 2
    # IsAlive True
    # MyThread 1
    # MyThread 2
    # MyThread 3
    # MyThread 4
    # MyThread 5
    # MyThread 6
    # MyThread 7
    # MyThread 8
    # MyThread 9
###############################################################################

(二)线程同步

同步机制

“锁” threading.RLock

acquire() 获取锁方法,进入locked状态,其他进程试图获得这个锁将变为blocked状态

release() 释放锁方法,进入unlocked状态

修改共享数据代码放置在acquire()和release()之间

“条件变量” threading.Condition

wait() 线程释放锁,进入blocked状态

notify() 唤醒blocked状态的线程

notifyAll() 唤醒所有的blocked状态的线程

保证每一个wait()方法调用都有一个相对应的notify()调用,也可以调用notifyAll()方法以防万一

例子二:

import threading
import time

myLock = threading.RLock()

class MyThread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name = threadname)
    def run(self):
        print self.getName()
        myLock.acquire()
        self.add()
        myLock.release()
    def add(self):
        global shareData
        shareData += 1
        print 'shareData = ', shareData, 'time = ', time.ctime()

if __name__ == '__main__':
    shareData = 0
    for i in range(10):
        t1 = MyThread('MyThread %d' % i)
        t1.start()
        time.sleep(1)
    ###############################################################################
    # Console:
    #MyThread 0
    #shareData = 1 time = Wed Jan 16 23:16:35 2008
    #MyThread 1
    #shareData = 2 time = Wed Jan 16 23:16:36 2008
    #MyThread 2
    #shareData = 3 time = Wed Jan 16 23:16:37 2008
    #MyThread 3
    #shareData = 4 time = Wed Jan 16 23:16:38 2008
    #MyThread 4
    #shareData = 5 time = Wed Jan 16 23:16:39 2008
    #MyThread 5
    #shareData = 6 time = Wed Jan 16 23:16:40 2008
    #MyThread 6
    #shareData = 7 time = Wed Jan 16 23:16:41 2008
    #MyThread 7
    #shareData = 8 time = Wed Jan 16 23:16:42 2008
    #MyThread 8
    #shareData = 9 time = Wed Jan 16 23:16:43 2008
    #MyThread 9
    #shareData = 10 time = Wed Jan 16 23:16:44 2008
###############################################################################

例三:

from Queue import Queue
import threading
import random
import time

#Producer thread
class Producer(threading.Thread):
    def __init__(self, threadname, queue):
        threading.Thread.__init__(self, name = threadname)
        self.sharedata = queue
    def run(self):
        for i in range(20):
            print self.getName(), 'adding', i, 'to queue'
            self.sharedata.put(i)
            time.sleep(random.randrange(10)/10.0)
            print self.getName(), 'Finished'

#Consumer thread
class Consumer(threading.Thread):
    def __init__(self, threadname, queue):
        threading.Thread.__init__(self, name = threadname)
        self.sharedata = queue
    def run(self):
        for i in range(20):
            print self.getName(), 'got a value: ', self.sharedata.get()
            time.sleep(random.randrange(10)/10.0)
        print self.getName(), 'Finished'
#Main thread
def main():
    queue = Queue()
    producer = Producer('Producer', queue)
    consumer = Consumer('Consumer', queue)
    print 'Starting threads ...'
    producer.start()
    consumer.start()
    producer.join()
    consumer.join()
    print 'All threads have terminated.'
if __name__ == '__main__':
    main()

###############################################################################
#Starting threads ...
#Producer adding 0 to queue
#Consumer got a value: 0
#Producer Finished
#Producer adding 1 to queue
#Consumer got a value: 1
#Consumer got a value: Producer Finished
#Producer adding 2 to queue
#2
#Consumer got a value: Producer Finished
#Producer adding 3 to queue
#3
#Consumer got a value: Producer Finished
#Producer adding 4 to queue
#4
#Consumer got a value: Producer Finished
#Producer adding 5 to queue
#5
#Consumer got a value: Producer Finished
#Producer adding 6 to queue
#6
#Producer Finished
#Producer adding 7 to queue
#Consumer got a value: 7
#Producer Finished
#Producer adding 8 to queue
#Producer Finished
#Producer adding 9 to queue
#Consumer got a value: 8
#Consumer got a value: 9
#Producer Finished
#Producer adding 10 to queue
#Producer Finished
#Producer adding 11 to queue
#Producer Finished
#Producer adding 12 to queue
#Consumer got a value: 10
#Consumer got a value: 11
#Producer Finished
#Producer adding 13 to queue
#Consumer got a value: 12
#Producer Finished
#Producer adding 14 to queue
#Consumer got a value: 13
#Producer Finished
#Producer adding 15 to queue
#Consumer got a value: 14
#Consumer got a value: 15
#Consumer got a value: Producer Finished
#Producer adding 16 to queue
#16
#Consumer got a value: Producer Finished
#Producer adding 17 to queue
#17
#Producer Finished
#Producer adding 18 to queue
#Consumer got a value: 18
#Consumer got a value: Producer Finished
#Producer adding 19 to queue
#19
#Consumer Finished
#Producer Finished
#All threads have terminated.
###############################################################################


类别:技术积累 | 添加到搜藏 | 分享到i贴吧 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu