多线程之信号量、事件与队列

# #信号量
# num = 0
# lock = threading.Lock()                 #加入进程锁
# semaphore = threading.BoundedSemaphore(5)  #最多允许5个进程同时运行
# def run(n):
#     semaphore.acquire()
#     #lock.acquire()             #获取锁
#     global num
#     num += 1
#     time.sleep(1)             #加入sleep就会变成串行,等待时间释放锁
#     #lock.release()             #释放锁
#     semaphore.release()
#     print num
#
# t_obj = []
#
# for i in range(50):
#     t1 = threading.Thread(target=run, args=('x%s'%i,))
#     t1.start()
#     t_obj.append(t1)
# for i in t_obj:
#     i.join()
#
# print 'now num is ',num
#事件,两个线程之间的交互
event = threading.Event()
def light():
    count = 0
    event.set()
    while True:
        if count >5 and count <10:    #变红灯
            event.clear()   #清除标志位
            print '33[41;1mred lingt is on...33[0m '
        elif count>10:
            event.set()     #设置标志位 变绿灯
            count = 0
            print '33[42;1mgreen lingt is on...33[0m '
        else:
            print '33[42;1mgreen lingt is on...33[0m '

        time.sleep(1)
        count +=1

def car():
    while True:
        if event.is_set():   #代表是绿灯
            print 'running'
        else:
            print 'waiting'
            event.wait()
            print 'begain run'
        time.sleep(1)
# light = threading.Thread(target=light)
# car1 = threading.Thread(target=car)
# light.start()
# car1.start()

#队列 queue 
作用:1、使程序解耦
     2、提高处理效率
import Queue
# q = Queue.Queue()   #先入先出
# #q = Queue.Queue(maxsize=3)  设置队列的最大值
# q.put('d1')
# q.put('d2')
# q.put('d3')
# print q.qsize()
# print q.get()
# print q.get()
# print q.get()
# #q.get()    #如果队列里面没有内容会锁死
# #解决锁死的两种办法,put也可以加block和timeout参数或者使用q.get_nowait()
# q.get(block=False)
# q.get(timeout=1)
#
# q = Queue.LifoQueue() #后进先出
# q1 = Queue.PriorityQueue()#可以设置优先级
# q.put((10,'a'))  #设置的方法(数字代表的是优先级,)优先级高的先出。
# q.put((6,'b'))
# q.put((-1,'v'))
# q.put((0,'d'))


#生产者消费者模型
q = Queue.Queue(maxsize=10)
def Producer():
    count = 0
    while True:
         q.put('baozi%s'%count)
         count +=1
         print "生产了%s包子"%count
         time.sleep(1)

def Consumer(name):
    #while q.qsize()>0:
    while True :
        print '%s 取到包子%s'%(name,q.get())

p = threading.Thread(target=Producer)
c = threading.Thread(target=Consumer,args=('xiaoming',))
d = threading.Thread(target=Consumer,args=('xiaohong',))
p.start()
c.start()
d.start()
原文地址:https://www.cnblogs.com/qiangayz/p/8621020.html