"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Share Locks Between Python Processes

How to Share Locks Between Python Processes

Published on 2024-11-08
Browse:311

How to Share Locks Between Python Processes

Sharing Locks Among Python Processes

When attempting to use a lock between multiple processes, you may encounter the error, "Lock objects should only be shared between processes through inheritance."

To resolve this, there are two main approaches:

Using a Manager

This approach involves creating a Manager object and passing a Manager.Lock():

from multiprocessing import Manager
...
m = Manager()
l = m.Lock()

Using a Manager, however, introduces the need for an additional process to host the Manager server and communicates through IPC.

Passing the Lock at Pool Creation

An alternative method is to pass the regular multiprocessing.Lock() at Pool creation time using the initializer keyword argument:

def init(l):
    global lock
    lock = l

l = multiprocessing.Lock()
pool = multiprocessing.Pool(initializer=init, initargs=(l,))

This method makes the lock instance global in all the child workers. Note that this approach eliminates the need for the partial function.

By employing one of these techniques, you can effectively share locks between Python processes, allowing for coordinated access to shared resources.

Release Statement This article is reprinted at: 1729132333 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3