-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06a_blocking_queue.py
More file actions
51 lines (34 loc) · 1.04 KB
/
Copy pathexer06a_blocking_queue.py
File metadata and controls
51 lines (34 loc) · 1.04 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
'''
BLOCKING QUEUE IMPLEMENTATION
Version A: Synchronous queues
'''
import time
import threading
class SynchronousQueue:
def __init__(self):
self.__sem_put = threading.Semaphore(1)
self.__sem_take = threading.Semaphore(0)
self.__element = None
def put(self, value):
self.__sem_put.acquire()
self.__element = value
self.__sem_take.release()
def take(self):
self.__sem_take.acquire()
result = self.__element
self.__sem_put.release()
return result
def producer(syncq: SynchronousQueue):
arr = [ 'lorem', 'ipsum', 'dolor' ]
for data in arr:
print(f'Producer: {data}')
syncq.put(data)
print(f'Producer: {data} \t\t\t[done]')
def consumer(syncq: SynchronousQueue):
time.sleep(5)
for _ in range(3):
value = syncq.take()
print(f'\tConsumer: {value}')
syncqueue = SynchronousQueue()
threading.Thread(target=producer, args=(syncqueue,)).start()
threading.Thread(target=consumer, args=(syncqueue,)).start()