python-26-线程队列

115 阅读1分钟
import queue#线程队列
#先进先出
# q=queue.Queue(3)#FIFO
# q.put(12)
# q.put('hello')
# q.put({'name':'femg'})
#
# while 1:
#     data = q.get()
#     print(data)

#先进后出
#q=queue.LifoQueue()
# q.put(12)
# q.put('hello')
# q.put({'name':'femg'})
# while 1:
#     data = q.get()
#     print(data)

#优先级
q=queue.PriorityQueue()
q.put([3,12])
q.put([2,'hello'])
q.put([4,{'name':'femg'}])

print(q.qsize())
print(q.empty())
print(q.full())

while 1:
    data = q.get()
    print(data)

生产者消费者模式

import time,random
import queue,threading

q = queue.Queue()

def Producer(name):
  count = 0
  while count <10:
    print("making........")
    time.sleep(5)
    q.put(count)
    print('Producer %s has produced %s baozi..' %(name, count))
    count +=1
    q.task_done()
    #q.join()
    print("ok......")
def Consumer(name):
  count = 0
  while count <10:
    time.sleep(1)
    print('还没做好,我在等待中')
    q.join()
    data = q.get()
    #q.task_done()

    print(data)
    print('\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data))

    count +=1

p1 = threading.Thread(target=Producer, args=('A',))
c1 = threading.Thread(target=Consumer, args=('B',))
#c2 = threading.Thread(target=Consumer, args=('C',))
#c3 = threading.Thread(target=Consumer, args=('D',))
p1.start()
c1.start()
# c2.start()
# c3.start()