Search⌘ K
AI Features

Locks and Logging

Explore how to manage concurrency in Python's multiprocessing module by using locks to prevent process interference. Understand the challenges of logging in multiprocessing and learn how to set up basic logging to avoid message mix-ups between processes.

Lock

The multiprocessing module supports locks in much the same way as the threading module does. All you need to do is import Lock, acquire it, do something and release it.

How multiprocessing module supports locks

Let’s take a look:

Python 3.5
from multiprocessing import Process, Lock
def printer(item, lock):
"""
Prints out the item that was passed in
"""
lock.acquire()
try:
print(item)
finally:
lock.release()
if __name__ == '__main__':
lock = Lock()
items = ['tango', 'foxtrot', 10]
for item in items:
p = Process(target=printer, args=(item, lock))
p.start()

Here we create a simple printing ...