-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrun_with_lock.py
More file actions
33 lines (29 loc) · 790 Bytes
/
run_with_lock.py
File metadata and controls
33 lines (29 loc) · 790 Bytes
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
from threading import Thread, Lock
import time
import random
queue = []
lock = Lock()
class ProducerThread(Thread):
def run(self):
nums = range(5)
global queue
while True:
num = random.choice(nums)
lock.acquire()
queue.append(num)
print "produced: ", num
lock.release()
time.sleep(random.random())
class ConsumerThread(Thread):
def run(self):
global queue
while True:
lock.acquire()
if not queue:
print "nothing in queue, but try to consume"
num = queue.pop(0)
print "consumed: ", num
lock.release()
time.sleep(random.random())
ProducerThread().start()
ConsumerThread().start()