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