python多线程2线程应用

上代码。。

'''

1、经典的生产者,消费者问题

2、Lock和RLock差不多:Lock会死锁,RLock不会,具体google

'''

#coding:gbk
'''
Created on 2013-1-4

@author: Jimmy

@note: 1、一个简单的创建线程例子,外加生产者消费者问题
        2、线程同步初步
'''
import log
import time
import threading

phone = 0


class Mthread(threading.Thread):     #Mthread类继承自threading.Thread类   
    def __init__(self, ThreadName):    
        #重写__init__方法的时候要记得调用基类的__init__方法   
        threading.Thread.__init__(self,name = ThreadName)
           
    def run(self):  #重写run()方法,把自己的线程函数的代码放到这里
        #func
        pass

#生产者
class Producer(Mthread):
    def __init__(self, lock, ProducerName = "Producer"):
        Mthread.__init__(self, ProducerName)
        self.lock = lock
        pass
    def run(self):
        global phone
        while 1:
            self.lock.acquire()
            phone += 1
            print "生产一个"
            print "Produce Now: " + self.getName() + " phoneNum = " + str(phone)
            self.lock.release()
            time.sleep(5)
#消费者
class Consumer(Mthread):
    def __init__(self, lock, ConsumerName = "Consumer"):
        Mthread.__init__(self, ConsumerName)
        self.lock = lock
        pass
    def run(self):
        global phone
        while 1:
            self.lock.acquire()
            if phone < 1:
                print "没有电话了,sleep 1s"
                self.lock.release()
                time.sleep(1)
            else:
                phone -= 1
                print "消费一个,sleep 3s"
                print "Consume Now: " + self.getName() + " phoneNum = " + str(phone)
                self.lock.release()
                time.sleep(3)
    
#同步的操作
class sync():
    def __init__(self):
        pass
    
if __name__ == "__main__":
    #===========================================================================
    # Mlog = log.logger()
    # Mlog.log("Create Thread Method")
    #===========================================================================
    lock = threading.RLock()
    #2个生产者
    p0 = Producer(lock,"p0").start()
    p1 = Producer(lock,"p1").start()
    p2 = Producer(lock,"p2").start()

    #3个消费者
    c0 = Consumer(lock,"c0").start()
    c1 = Consumer(lock,"c1").start()
    c2 = Consumer(lock,"c2").start()
    
    

 

 

posted @ 2013-01-05 10:11  2012harry  阅读(198)  评论(0编辑  收藏  举报