Day9 process synchronization Lock process queue process pool production consumption model

Source: Internet
Author: User
Tags mutex

Process Sync Lock:

When running the program, it is possible that your program open multiple processes at the same time, the process will be a number of execution results printed out, so that the printed information is chaotic, how to ensure that the printing information is orderly?

In fact, it is equivalent to let the process exclusive resources.

1  fromMultiprocessingImportProcess,lock#Reference Function2 Import Time3 defWork (Name,mutex):4Mutex.acquire ()#Join the lock here5     Print('task <%s> is runing'%name)6Time.sleep (2)7     Print('task <%s> is done'%name)8Mutex.release ()#must be unlocked after the lock is added9 Ten if __name__=='__main__': Onemutex=Lock () AP1=process (target=work,args= ('Egon', mutex)) -P2=process (target=work,args= ('Alex', mutex)) - P1.start () the P2.start () -     Print('Master')

For example, the function of simulating the ticket:

To write a text first ("Count": 1) just count it.

1 ImportJSON2 ImportOS3 Import Time4  fromMultiprocessingImportProcess,lock5 defsearch ():6Dic=json.load (Open ('Db.txt'))7     Print('\033[32m[%s] See the number of votes left <%s>\033[0m'% (Os.getpid (), dic['Count']))8 defget_ticket ():9DIC = json.load (open ('Db.txt'))TenTime.sleep (0.5)#Network latency for analog read databases One     ifdic['Count'] >0: Adic['Count']-=1 -Time.sleep (0.5)#network latency for simulating write databases -Json.dump (Dic,open ('Db.txt','W')) the         Print('\033[31m%s Purchase ticket success \033[0m'%os.getpid ()) - defTask (Mutex): - Search () - Mutex.acquire () + Get_ticket () - mutex.release () + if __name__=='__main__': Amutex=Lock () at      forIinchRange (10): -P=process (target=task,args=(mutex,)) -P.start ()

Process queue:

How to share memory:

1  fromMultiprocessingImportProcess,manager,lock #Manager共享内存函数2 3 defTask (Dic,mutex):4 With Mutex:5dic['Count']-=16 7 if __name__=='__main__':8mutex=Lock ()9m=Manager ()TenDic=m.dict ({'Count': 100}) OneP_l=[] A      forIinchRange (100): -P=process (target=task,args=(Dic,mutex)) - p_l.append (P) the P.start () -  -      forPinchp_l: - P.join () +     Print(DIC)


Queue:

Processes are isolated from each other to enable interprocess communication

1  fromMultiprocessingImportQueue#Reference Function2Q=queue (3)#意味着你队列长队最大为三34Q.put (' First')5Q.put ('Second')6Q.put ('Third')7 #q.put (' fourth ') #满了的话会一直卡住8 9 Print(Q.get ())Ten Print(Q.get ()) One Print(Q.get ()) A Print(Q.get ()) -  - #Understand the #Q=queue (3) - #  - #q.put (' first ', Block=false) - #q.put (' second ', Block=false) + #q.put (' third ', Block=false) #这样的话队列满了就会抛出异常, will not be stuck here - ## q.put_nowait (' fourth ')
#q. Put (' fourth ', Block=false) A #q.put (' fourth ', timeout=3) #指定抛出时间 if the queue is still full after 3 seconds throws an exception

Producer Consumer Model:

Day9 process synchronization Lock process queue process pool production consumption model

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.