Network programming-data isolation between processes, daemons

Source: Internet
Author: User
Tags semaphore ticket

The data between the process and the process is isolated
Memory space is not shared
So if you want to communicate, you have to use other means and both processes are voluntary. The result of the execution of the child process the parent process cannot get
How the parent process gets the execution result of the child process???
Communication between parent and child processes via socket
 fromMultiprocessingImportPROCESSN= 100deffunc ():GlobalN N= N-1return111if __name__=='__main__': n_l= []     forIinchRange (100): P= Process (target=func) P.start () N_l.append (p) forPinchN_l:p.join ()Print(n)

2 Daemon Process

The setup daemon ends directly after the main process's code executes, regardless of whether the daemon finishes

Application Scenarios

Reporting the Living master process is alive
100 Machines 100 Processes 10000 processes
Whether the app is working properly-task Manager to view
How the daemon reports live to the monitoring mechanism??? send/Write Database
Why use a daemon to report a job? Why not work with the main process???
The daemon does not consume CPU or require the operating system to dispatch
The main process can send a message every 60s strictly

Example one:

Import Time fromMultiprocessingImportProcessdeffunc1 ():Print("begin") Time.sleep (3)    Print("Wahaha")if __name__=='__main__': P=process (target=func1) P.daemon=True#The Daemon's properties, the default is False, if set to true, indicates that the child process is set as a daemon    ## The daemon operation should be set before the child process is openedP.start () time.sleep (1)    Print("Main program")

Example two:

Import Time fromMultiprocessingImportProcessdeffunc1 ():Print("begin") Time.sleep (3)    Print("Wahaha")defFunc2 (): whileTrue:Print("In Finc2") Time.sleep (0.5)if __name__=='__main__': Process (Target=func1). Start () P=process (target=func2) P.daemon=True#The Daemon's properties, the default is False, if set to true, indicates that the child process is set as a daemon    ## The daemon operation should be set before the child process is openedP.start () time.sleep (1)    Print("Main program")    #after being set as a daemon    #What effect would it have ?    #The daemon will end directly after the code of the main process has finished executing, without

Basic use of all processes

Process: A lot of things can be done at the same time without affecting each other

Socket TCP Server

Use multi-process knowledge points to resolve native sockets only with one conn to communicate at the same time

Server Side

ImportSocket fromMultiprocessingImportProcessdefTalk (conn):Try:         whileTrue:conn.send (b'Hello')            Print(CONN.RECV (1024))    finally: Conn.close ()if __name__=='__main__': SK=socket.socket () Sk.bind ('127.0.0.1', 9091) ) Sk.listen ()Try:         whiletrue:conn,addr=sk.accept () Process (target=talk,args=(conn,)). Start ()finally: Sk.close ()

Client Side

Import Socket Import  = socket.socket () sk.connect (('127.0.0.1', 9091))while  True:    Print(SK.RECV (1024x768))    sk.send (str (os.getpid ()). Encode ( ' Utf-8 '))

The heavy *********************************** of the lock weight

When multiple processes share a piece of data, the data can become unsafe,
Locks are required to maintain data security

Lock = Lock () # Creates a lock
Lock.acquire () # Get the key to this lock
Lock.release () # Return the key to this lock

Example One

 fromMultiprocessingImportLock fromMultiprocessingImportProcessImportJSONImport Time fromMultiprocessingImportLock fromMultiprocessingImportProcessdefSearch (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) time.sleep (0.2)    ifcount_dic['Count'] >0:count_dic['Count']-= 1Print('The person %s purchased the ticket successfully'%i) Time.sleep (0.2) with open ('DB','W') as F:json.dump (count_dic,f)defTask (I,lock): Search (i) lock.acquire ()#if it had been acquire and not been release, then the process would be blocked here.Buy (i) lock.release ()if __name__=='__main__': Lock=Lock () forIinchRange (10): P= Process (target=task,args=(I,lock)) P.start ()

Example two signal volume many bar keys correspond to a lock lock+count

Ktv
4 Small Houses
10 people standing outside the house to play.

 fromMultiprocessingImportProcess fromMultiprocessingImportSemaphoreImport TimeImportRandom fromMultiprocessingImportProcess,semaphoredefKTV (Num,sem): Sem.acquire ()Print('person%s into the KTV'%num) time.sleep (Random.randint (1,4))    Print('person%s out of the KTV'%num) sem.release ()if __name__=='__main__': Sem= Semaphore (4)     forIinchRange (10): P= Process (target=ktv,args=(I,sem)) P.start ()

3 Events

Wait () method waits
Block if this flag is false then block
Non-blocking if this flag is true then it is non-blocking
View Flag Is_set ()
Modify Flag

Set () sets the flag to True

Clear () sets the flag to False

E =Event ()Print(E.is_set ())#default is False at the beginning of event creationE.set ()#set Flag to True Print(E.is_set ()) e.wait ()#It's the equivalent of no pass.E.clear ()#set flag to FalseE.wait ()#Block ForeverE.wait (timeout=10)#if the signal becomes true within the blocking 10s, then it does not continue to block the direct pass,                    #if the state remains unchanged after blocking 10s, continue,Print(E.is_set ())#no matter if the timeout of the previous wait is passed, my status will not change.

Traffic light model

The process of controlling traffic lights

 fromMultiprocessingImportevent,processImport TimeImportRandomdefTraffic_light (E):Print('\033[1;31m red light \033[0m')     whileTrue:time.sleep (2)        ifE.is_set ():Print('\033[1;31m red light \033[0m') e.clear ()Else:            Print('\033[1;32m green light \033[0m') E.set ()#car, etc. or throughdefcar (id,e):if  notE.is_set ():Print('Car%s waits'%ID) e.wait ()Print('car%s through'%ID)defPolice_car (id,e):if  notE.is_set (): e.wait (Timeout= 0.5)    Print('police car%s through'%ID)#The main process starts the traffic control lights the process of starting the carif __name__=='__main__': E=Event () p= Process (target=traffic_light,args=(E,)) P.start () Car_lst=[Car,police_car] forIinchRange (20): P= Process (Target=random.choice (car_lst), args=(i,e)) P.start () time.sleep (random.randrange (0,3,2))

Network programming-data isolation between processes, daemons

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.