forked from xiao-xiaoming/DataStructure-BeautyOfAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblocking_queue.py
More file actions
64 lines (52 loc) · 1.67 KB
/
Copy pathblocking_queue.py
File metadata and controls
64 lines (52 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# -*- coding: utf-8 -*-
__author__ = 'xiaoxiaoming'
import queue
import random
import threading
import time
class Producer(threading.Thread):
nameList = ["apple", "peach", "pineapple", "orange", "banana", "blueberry"]
flag = 1
def __init__(self, q, name):
threading.Thread.__init__(self)
self.name = name
self.q = q
def run(self):
name_list = Producer.nameList
while Producer.flag:
queueLock.acquire()
if not self.q.full():
data = name_list[random.randrange(0, len(name_list))]
self.q.put(data)
print("%s 生产数据: %s" % (threading.currentThread().name, data))
queueLock.release()
else:
queueLock.release()
time.sleep(random.random() * 3)
class Consumer(threading.Thread):
flag = 1
def __init__(self, q, name):
threading.Thread.__init__(self)
self.name = name
self.q = q
def run(self):
while Consumer.flag:
queueLock.acquire()
if not self.q.is_empty():
data = self.q.get()
print("%s 消费数据: %s" % (threading.currentThread().name, data))
queueLock.release()
else:
queueLock.release()
time.sleep(random.random() * 4)
workQueue = queue.Queue(5)
queueLock = threading.Lock()
# 创建新线程
Producer(workQueue, "Producer1").start()
Producer(workQueue, "Producer2").start()
Consumer(workQueue, "Consumer1").start()
Consumer(workQueue, "Consumer2").start()
Consumer(workQueue, "Consumer3").start()
while 1:
time.sleep(1)
print(workQueue.queue)