-
Notifications
You must be signed in to change notification settings - Fork 0
/
soft.py
107 lines (90 loc) · 3.06 KB
/
soft.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import threading
import time
import queue
from src.ProcessManager.Semaphore import Semaphore
# 初始化信号量
sign = Semaphore(5)
# 生产者线程
class ProducerThread(threading.Thread):
def run(self):
numbers = range(1, 6)
global task_queue
while True:
# 获取队列锁
queue_lock.acquire()
if task_queue.full():
# 如果队列已满,释放队列锁并等待
queue_lock.release()
time.sleep(1)
else:
# 如果队列未满,将数据放入队列中
for number in numbers:
task_queue.put(number)
print("生产者生产数据:", number)
# 释放队列锁
queue_lock.release()
time.sleep(2)
# 消费者线程
class ConsumerThread(threading.Thread):
def run(self):
global task_queue
while True:
# 获取队列锁
queue_lock.acquire()
if task_queue.empty():
# 如果队列为空,释放队列锁并等待
queue_lock.release()
time.sleep(1)
else:
# 如果队列不为空,从队列中取出数据并进行消费
number = task_queue.get()
print("消费者消费数据:", number)
# 释放队列锁
queue_lock.release()
time.sleep(2)
# 创建一个线程安全的队列
queue_lock = threading.Lock()
task_queue = queue.Queue(maxsize=5)
# 生产者线程
class ProducerThread(threading.Thread):
def run(self):
numbers = range(1, 6)
global task_queue
while True:
# 获取队列锁
queue_lock.acquire()
if task_queue.full():
# 如果队列已满,释放队列锁并等待
queue_lock.release()
time.sleep(1)
else:
# 如果队列未满,将数据放入队列中
for number in numbers:
task_queue.put(number)
print("生产者生产数据:", number)
# 释放队列锁
queue_lock.release()
time.sleep(2)
# 消费者线程
class ConsumerThread(threading.Thread):
def run(self):
global task_queue
while True:
# 获取队列锁
queue_lock.acquire()
if task_queue.empty():
# 如果队列为空,释放队列锁并等待
queue_lock.release()
time.sleep(1)
else:
# 如果队列不为空,从队列中取出数据并进行消费
number = task_queue.get()
print("消费者消费数据:", number)
# 释放队列锁
queue_lock.release()
time.sleep(2)
# 创建并启动生产者和消费者线程
producer_thread = ProducerThread()
consumer_thread = ConsumerThread()
producer_thread.start()
consumer_thread.start()