Chinaunix首页 | 论坛 | 博客
  • 博客访问: 298652
  • 博文数量: 34
  • 博客积分: 2375
  • 博客等级: 大尉
  • 技术积分: 354
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-09 05:49
文章存档

2013年(1)

2012年(3)

2011年(10)

2010年(20)

我的朋友

分类: Python/Ruby

2010-09-28 14:13:28

在用python的threading.Thread编写多线程程序时,最简单的就是是用锁,为使线程之间保持同步,可以使用threading.Condition() 条件变量

思路:

1.分析哪一块空间需要多线程读写,抽象出一个共享空间类,对共享空间设置读方法(get)和写方法(set)

2.为使读线程和写线程同步,可以用threading.Condition()产生一个条件,同一个条件有wait()和notify()
notifyAll()方法,wait使线程自己进入block(阻塞)状态,一个线程的notify可以使同一个条件变量中block
的线程得到运行的机会。notifyAll通知所有被阻塞的线程进入runnable状态。

3.所有对共享空间操作的方法(read or write)都封闭在acquire()和release()中间

========以下实例简单明了==================

 

#coding=utf-8
#file name is maker.py

import threading
import random,time

class Maker(threading.Thread):
    
    def __init__(self,threadName,shareObject):
        threading.Thread.__init__(self,name=threadName)
        self.shareObject=shareObject
        
    def run(self):
        for x in range(1,5):
            time.sleep(random.randrange(1,4))
            self.shareObject.set(x)
            print "%s threading write %d" %(threading.currentThread().getName(),x)

 

=============================================================================


 

#coding=utf-8
#file name is user.py

import threading
import time,random

class User(threading.Thread):
    
    def __init__(self,threadName,shareObject):
        threading.Thread.__init__(self,name=threadName)
        self.shareObject=shareObject
        self.sum=0
        
    def run(self):
        for x in range(1,5):
            time.sleep(random.randrange(1,4))
            tempNum=self.shareObject.get()
            print "%s threading read %d" %(threading.currentThread().getName(),tempNum)
            self.sum=self.sum+tempNum
            
    def display(self):
        print "sum is %d" %(self.sum)


 

=============================================================================

 

#coding=utf-8
#file name is shareInt.py

import threading
import time,random

class ShareInt():
    
    def __init__(self):
        self.threadCondition=threading.Condition()
        self.shareObject=[]
        
        
    #所有对共享空间操作的方法(read or write)都封闭在acquire()和release()中间
    def set(self,num):
        self.threadCondition.acquire() # 在调用一个读或者写共享空间的方法时,需要先拿到一个基本锁
                                                          # 基本锁的获得采用竞争机制,无法判断哪个线程会先运行
                                                  # 不拿基本锁会出现运行时错误:cannot notify on un-aquired lock
        
        if len(self.shareObject)!=0:
            print "%s threading try write! But shareObject is full" %(threading.currentThread().getName())
            self.threadCondition.wait() # 在条件满足的情况下,会block掉调用这个方法的线程
                               # 这里使用while语句更好,因为block在这个位置后,
                               # 当再次运行此线程的时候,会从头再一次检查条件。
        
        self.shareObject.append(num)
        
        self.threadCondition.notify() # 一定要先调用notify()方法,在release()释放基本锁
        self.threadCondition.release() # 可以理解为"通知"被wait的线程进入runnable状态,然后在它获得锁后开始运行
                                                          # 最后一定要release()释放锁,否则会导致死锁
                                         
    def get(self):
        self.threadCondition.acquire()
        
        if len(self.shareObject)==0:
            print "%s threading try read! But shareObject is empty" %(threading.currentThread().getName())
            self.threadCondition.wait()
            
        tempNum=self.shareObject[0]
        self.shareObject.remove(tempNum)
        self.threadCondition.notify()
        self.threadCondition.release()
        return tempNum

 

==============================测试代码===============================


 

#coding=utf-8
#file name is Test.py

from user import User
from maker import Maker
from shareInt import ShareInt

shareObject=ShareInt()
user1=User("user1",shareObject)
maker1=Maker("maker1",shareObject)

user1.start()
maker1.start()

user1.join()
maker1.join()

user1.display()

print "main threading over!"


阅读(12995) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~