Synchronization methods are basically the same as multithreading.
1) Lock
Lock can be used to avoid access conflicts when multiple processes require access to shared resources.
Copy Code code as follows:
Import multiprocessing
Import Sys
def worker_with (lock, F):
With Lock:
FS = open (f, "A +")
Fs.write (' Lock acquired via with\n ')
Fs.close ()
def worker_no_with (lock, F):
Lock.acquire ()
Try
FS = open (f, "A +")
Fs.write (' Lock acquired directly\n ')
Fs.close ()
Finally
Lock.release ()
if __name__ = = "__main__":
f = "file.txt"
Lock = multiprocessing. Lock ()
W = multiprocessing. Process (Target=worker_with, args= (lock, F))
NW = multiprocessing. Process (Target=worker_no_with, args= (lock, F))
W.start ()
Nw.start ()
W.join ()
Nw.join ()
In the above example, if two processes do not use lock to synchronize, their write operations to the same file may be confusing.
2) Semaphore
Semaphore is used to control the number of accesses to a shared resource, such as the maximum number of connections to a pool.
Copy Code code as follows:
Import multiprocessing
Import time
def worker (S,i):
S.acquire ()
Print (Multiprocessing.current_process (). Name + "Acquire")
Time.sleep (i)
Print (Multiprocessing.current_process (). Name + "Release")
S.release ()
if __name__ = = "__main__":
s = multiprocessing. Semaphore (2)
For I in range (5):
p = multiprocessing. Process (Target=worker, args= (s,i*2))
P.start ()
The above example uses semaphore to limit up to 2 processes executing concurrently.
3) Event
Event is used to implement interprocess communication between processes.
Copy Code code as follows:
Import multiprocessing
Import time
def wait_for_event (E):
Print (' wait_for_event:starting ')
E.wait ()
Print (' Wait_for_event:e.is_set ()-> ' + str (e.is_set ()))
def wait_for_event_timeout (E, T):
"" "Wait t seconds and then timeout" ""
Print (' wait_for_event_timeout:starting ')
E.wait (t)
Print (' Wait_for_event_timeout:e.is_set ()-> ' + str (e.is_set ()))
If __name__ = = ' __main__ ':
e = multiprocessing. Event ()
w1 = multiprocessing. Process (name= ' block ',
Target=wait_for_event,
Args= (E,))
W1.start ()
W2 = multiprocessing. Process (name= ' Non-block ',
Target=wait_for_event_timeout,
Args= (E, 2))
W2.start ()
Time.sleep (3)
E.set ()
Print (' main:event is set ')
#the output is:
#wait_for_event_timeout: Starting
#wait_for_event: Starting
#wait_for_event_timeout: E.is_set ()->false
#main: Event is set
#wait_for_event: E.is_set ()->true