Multi-process + semaphore semaphore

Source: Internet
Author: User
Tags semaphore

Use the following example to understand.

 fromMultiprocessingImportProcess fromMultiprocessingImportSemaphoreImportdatetimeImport TimeImportMultiprocessingdefworker (S, i): S.acquire ()Print(Multiprocessing.current_process (). Name +"Acquire", Datetime.datetime.now ()) time.sleep (i)Print(Multiprocessing.current_process (). Name +"Release", Datetime.datetime.now (),"\ n") s.release ()if __name__=="__main__": S= multiprocessing. Semaphore (2)     forIinchRange (5): P= multiprocessing. Process (target = worker, args= (s, i*2) ) P.start ()

Operation Result:

Analysis:p = multiprocessing. Process (...) Five processes are defined, P.start five processes in parallel, resulting in semaphore causes. s = multiprocessing. Semaphore (2) defines a maximum semaphore of 2,release: +1 acquire: 122:41:30in the first step, five processes execute concurrently, Process 1 executes and waits for a 0s,s-1=1Step two, five processes execute concurrently, Process 2 executes and waits for 2s,s-1=0The third step is because process 1 executes, and the wait time is 0, while process 2 waits for 2s. So this step must be process 1 execution, and process 1 executes, and the semaphore is +1 and goes non-clogging. Fourth step, process 2 goes into wait 2s, so only three processes 3, 4, 5 parallel, Process 4 executes and waits for 6s,s-1=022:41:32Fifth Step, process 2 wait 2s complete, process 2 Execute, s+1=1sixth step, process 4 waits, only two processes 3, 5 parallel, Process 3 executes and waits for 4s,s-1=022:41:36seventh Step, process 4 waits for 6s, process 3 is 4s, so process 3 executes, s+1=1eighth step, process 4 waits, process 5 executes and waits for 8s,s-1=0nineth Step, Process 4 execution, s+1=122:41:44Tenth step, process 5 execution, s-1=0

Multi-process + semaphore semaphore

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.