-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprodcons_mutex.py
More file actions
79 lines (62 loc) · 1.9 KB
/
prodcons_mutex.py
File metadata and controls
79 lines (62 loc) · 1.9 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
from random import randint
from time import sleep
from Queue import Queue
from mythread import My_thread
from threading import RLock
QUEUE_SIZE = 6
def writeQ(queue):
mutex_print ( 'Producing object for Q...' )
if queue.full() :
mutex_print ( "queue is full, writeQ will block" )
block = True
else :
block = False
queue.put('xxx', block=1)
if block :
mutex_print ( "writeQ is now unblocked" )
mutex_print ( 'size now %d'% queue.qsize() )
def readQ(queue):
if queue.empty() :
mutex_print ( "readQ will block" )
block = True
else :
block = False
val = queue.get(block=1)
if block :
mutex_print ( "readQ is now unblocked" )
mutex_print ('consumed object from Q... size now %d' % queue.qsize() )
def writer(queue, loops):
for i in range(loops):
writeQ(queue)
sleep(randint(1, 3))
def reader(queue, loops):
for i in range(loops):
readQ(queue)
sleep(randint(2, 5))
def mutex_print( string ):
"""If you have multiple threads printing at random, then the output looks
awful. Using a lock around a print statement insures that only one thread can
print at any time. All other threads that wish to print block when they try to
acquire the lock, until the thread that blocks the lock releases it"""
print_lock.acquire()
print string
print_lock.release()
funcs = [writer, reader]
nfuncs = range(len(funcs))
print_lock = RLock()
def main():
nloops = 20
q = Queue(QUEUE_SIZE)
threads = []
for i in nfuncs:
t = My_thread(funcs[i], (q, nloops), funcs[i].__name__)
threads.append(t)
for i in nfuncs:
threads[i].start()
for i in nfuncs:
threads[i].join()
# no need to invoke mutex_print here because all of the threads are terminated
print 'all DONE'
if __name__ == '__main__':
main()