简体   繁体   中英

Checking a multiprocessing.Value's value after getting the lock

Here is a code snippet:

from multiprocessing import Value
import os

v = Value('i', 0)

# The following code runs in multiple processes
if v.value == 0:
    with v.get_lock():
        if v.value == 0: # Is this line necessary?
            v.value = os.getpid()

Since the os.getpid() varies, do I need to do another check after getting the lock?

I could imagine the following process flow without the additional check after getting the lock:

  • P1 asks for the lock
  • P2 asks for the lock
  • P1 gets the lock and changes the value
  • P1 releases the lock
  • P2 gets the lock and changes the value
  • P2 releases the lock

The value will then be the one set by P2, even though P1 got the lock and changed it first.

Am I wrong about the asumptions I am making? Does adding an additional check after getting the lock fix the problem in every case? If so, is it considered a good practice?

I haven't used shared memory objects with multiprocessing but there is absolutely a race condition between if v.value == 0 and with v.get_lock() .

So yes you would need to test again.

More importantly maybe - as it says in the docs , you (or whoever reads this later) probably don't want to be sharing memory unless it is a carefully considered decision. Now you have processes waiting on each other which may kill the main benefit of multiprocessing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM