The posted code starts two async Processes. The first publisher
Process publishes data to the Queue
, the second subscriber
Process reads the data from the Queue
and logs it to console.
To make sure the Queue is not accessed at the same time, before getting the data from the Queue
, the subscribe
function first executes lock.acquire()
, then gets the data with data = q.get()
and finally releases the lock with the lock.release()
statement.
The same locking-releasing sequence is used in publish
function. But I had to comment two lines since acquiring the lock
in publish
function brings the script to halt. Why?
import multiprocessing, time, uuid, logging
log = multiprocessing.log_to_stderr()
log.setLevel(logging.INFO)
queue = multiprocessing.Queue()
lock = multiprocessing.Lock()
def publish(q):
for i in range(20):
data = str(uuid.uuid4())
# lock.acquire()
q.put(data)
# lock.release()
log.info('published: %s to queue: %s' % (data, q))
time.sleep(0.2)
def subscribe(q):
while True:
lock.acquire()
data = q.get()
lock.release()
log.info('.......got: %s to queue: %s' % (data, q))
time.sleep(0.1)
publisher = multiprocessing.Process(target=publish, args=(queue,))
publisher.start()
subscriber = multiprocessing.Process(target=subscribe, args=(queue,))
subscriber.start()