-
Notifications
You must be signed in to change notification settings - Fork 0
/
peterson_solution_alternative.py
67 lines (56 loc) · 1.95 KB
/
peterson_solution_alternative.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
import random
import time
import threading
import logging
import queue
BSIZE = 8 # Buffer size
PWT = 2 # Producer wait time limit
CWT = 10 # Consumer wait time limit
RT = 10 # Program run-time in seconds
def myrand(n):
return random.randint(1, n)
def producer(queue, state):
index = 0
while state:
time.sleep(1)
logging.info("\nProducer is ready now.")
with queue.lock:
if not queue.full():
tempo = myrand(BSIZE * 3)
logging.info(f"Job {tempo} has been produced")
queue.put(tempo)
logging.info(f"Buffer: {list(queue.queue)}")
else:
logging.info("Buffer is full, nothing can be produced!!!")
wait_time = myrand(PWT)
logging.info(f"Producer will wait for {wait_time} seconds")
time.sleep(wait_time)
def consumer(queue, state):
time.sleep(5)
while state:
time.sleep(1)
logging.info("\nConsumer is ready now.")
with queue.lock:
if not queue.empty():
job = queue.get()
logging.info(f"Job {job} has been consumed")
logging.info(f"Buffer: {list(queue.queue)}")
else:
logging.info("Buffer is empty, nothing can be consumed!!!")
wait_time = myrand(CWT)
logging.info(f"Consumer will sleep for {wait_time} seconds")
time.sleep(wait_time)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format='%(message)s')
shared_queue = queue.Queue(BSIZE)
shared_queue.lock = threading.Lock()
state = True
producer_thread = threading.Thread(target=producer, args=(shared_queue, state))
consumer_thread = threading.Thread(target=consumer, args=(shared_queue, state))
producer_thread.start()
consumer_thread.start()
time.sleep(RT)
state = False
producer_thread.join()
consumer_thread.join()
logging.info("\nThe clock ran out.")