A model of the process of concurrent programming: A tool for process synchronization (iii) following the creation process (daemon)

Source: Internet
Author: User
Tags semaphore ticket

Multiprocessing package in the process module :


Join () Blocking problem, can be understood as: the equivalent of each child process at the end of the parent process will send a message, join () is received, the internal socket implementation


1, data isolation issues between processes
Data between processes and processes is isolated and memory space cannot be shared, so you must use other methods to communicate. And both processes are voluntary.
The parent-child process communicates through the socket.
2, Daemon:
Daemon = True of the daemon's properties, the default is False if set to True indicates that the child process is set to a daemon. And the set daemon action should precede the word opening of the child process.
    The daemon ends directly after the execution of the main process's code, regardless of whether the daemon has finished executing. *******

1 deffunc1 ():2     Print('begin')3Time.sleep (3)4     Print('Wahaha')5 6 if __name__=='__main__':7p = Process (target=func1)8P.daemon =True9     #The Daemon's properties, the default is False, if set to true, indicates that the child process is set as a daemonTen     #the setting daemon should be preceded by a child process One P.start () A  -Time.sleep (1) -     Print('Main Process') the  - " " - Output Result: - Bigin + Main Process - " "
Example of Daemon (i)

Mainly applied to: newspaper live: report The main process is still alive.

1 deffunc1 ():2     Print('begin')3Time.sleep (3)4     Print('Wahaha')5 6 defFunc2 ():7      whileTrue:8         Print('In Func2')9Time.sleep (0.5)Ten  One if __name__=='__main__': AProcess (target=func1). Start () -p = Process (target=Func2) -P.daemon =True the P.start () -Time.sleep (1) -     Print('Main Process') - " " + Output Result: - begin + In Func2 A In Func2 at Main Process - Wahaha # does not execute the daemon's content again while waiting to print ' Wahaha ' - " "
Examples of daemons (ii)

Summary: Process: At the same time can do a lot of things, do not affect each other.


model of the process:   The Process Synchronization tool . PS: Sequential is synchronous, the process is asynchronous,


1. Lock lock Module : Guarantees a piece of code that can only be executed by one process at a time.
Lock = Lock () creates a lock
Acquire () Get the key to the lock
Release () return the key to this lock
PS: Non-security of multi-process data: When multiple processes share a piece of data, the data will appear unsafe and need to be locked to maintain the security of the data.

1 #The code involves a DP file, which is used to simply impersonate a common database on another machine .2 3 " "4 Rob Ticket Analysis:5 1, the customer can access the server at the same time, and access to the same number of votes6 2, when the customer makes a purchase request, the server must be synchronized, one by one.7 Q: How to implement synchronous processing of a function in a parallel asynchronous program8 " "9 Ten  One ImportJSON A Import Time -  fromMultiprocessingImportLock -  fromMultiprocessingImportProcess the defSearch (i): -With open ('DB','R') as F:count_dic =json.load (f) -Time.sleep (0.2) -     Print('Person %s Remainder ticket:%s sheet'% (i,count_dic['Count'])) +  - defBuy (i): +With open ('DB','R') as F:count_dic =json.load (f) ATime.sleep (0.2) at     ifcount_dic['Count'] >0: -count_dic['Count']-= 1 -         Print('The person %s purchased the ticket successfully'%i) -Time.sleep (0.2) -With open ('DB','W') as F:json.dump (count_dic,f) -  in defTask (I,lock): - Search (i) toLock.acquire ()#if it had been acquire and not been release, then the process would be blocked here. + Buy (i) - lock.release () the  * if __name__=='__main__': $Lock =Lock ()Panax Notoginseng      forIinchRange (10): -p = Process (target=task,args=(I,lock)) theP.start ()
example of lock grab ticket

2, Semaphore semaphore module : multiple keys corresponding to a lock

The essence is: Lock+count count to achieve

3, Incident event module :

Flag: At the beginning of the event, the flag defaults to False

Wait (Timeout=none) waits for a keyword parameter timeout (timeout) in seconds.
1, blocking, if the flag is false is blocking
2, non-blocking, if the flag is true is non-blocking
Is_set () View flag
Set () The value of the modifier flag is true
Clear () The value of the modified flag is false

1 Import Time2 ImportRandom3  fromMultiprocessingImportevent,process4 5 defTraffic_light (E):6     Print('\033[1;31m red light \033[0m')7      whileTrue:8Time.sleep (2)9         ifE.is_set ():Ten             Print('\033[1;31m red light \033[0m') One e.clear () A         Else: -             Print('\033[1;32m green light \033[0m') - E.set () the  -  - #car, etc. or through - defcar (id,e): +     if  notE.is_set (): -         Print('Car%s waits'%ID) + e.wait () A     Print('car%s through'%ID) at  - defPolice_car (id,e): -     if  notE.is_set (): -E.wait (Timeout = 0.5) -     Print('police car%s through'%ID) -  in #The main process starts the traffic control lights the process of starting the car - if __name__=='__main__': toE =Event () +p = Process (target=traffic_light,args=(E,)) - P.start () theCar_lst =[Car,police_car] *      forIinchRange (20): $p = Process (Target=random.choice (car_lst), args=(i,e))Panax Notoginseng P.start () -Time.sleep (Random.randrange (0,3,2))
Traffic light Model event

A model of the process of concurrent programming: A tool for process synchronization (iii) following the creation process (daemon)

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.