Python multi-process sync lock, Semaphore, event instance _python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.