Xxvii, multi-process, mutex

 

First, create a process

Create a process that is in memory to re-open a piece of memory space 
will allow the code generated throw into
a corresponding process in memory is a separate memory space, and there is no other relationship between variables is independent of

data between the process and the process is isolated you can not interact directly
but indirect interaction can be achieved through certain techniques
"" "
If you call the function, it is bound synchronization wait time ending finish, will execute other code is executed multiple processes at the same time here, without waiting. os.getpid () shows the number of processes
os.getppid ()) # query the current process of the parent who is 
the main program and subroutines in an asynchronous process is random run
in two ways:

 1. The first:   

from multiprocessing Import Process
 Import Time
 Import OS 


DEF Test (name):
     Print ( ' % S running IS ' % name, os.getpid ())
     Print ( ' child process parent: ' , os.getppid ()) 
    the time.sleep ( . 3 )
     Print ( ' % S over iS ' % name, os.getpid ())
     Print ( ' child process parent: ' , os.getppid ()) 


"" " 
manner windows will create a process code module from execution down again on 
linux directly code intact copy of


windows must create a process in if __name__ == '__main__': create an error in the code block or 
"" " 
IF  __name__ == ' __main__ ' : 
    the p- = Process (target = the Test, args = ( ' child process: ' ,))   # Sign create a process object p is a process object 
    p.start ()   # tell the operating system to help you open a child process, 
    Print ( ' parent: ' , os.getpid ())   # query the current process digital 
    Print ( ' parent parent: ' , os.getppid ())   # query the current process of the parent who is

2. The second method:

Import OS
 from multiprocessing Import Process 


class MyProcess (Process):
     DEF  the __init__ (Self, arg1, arg2): 
        . Super () the __init__ () # initialized to a parent class, the following is derived attributes 
        self.arg1 = arg1 
        self.arg2 = arg2 

    DEF RUN (Self):
         Print (self.arg1, self.arg2)
         Print (self.pid)   # equivalent to os.getpid () 
        Print (self.name)
         Print ( " child process: " , os.getpid ()) 


IF  __name__== ' __main__ ' :
     # Print ( "main process:", os.getpid ()) 
    P1 = MyProcess (1,2 ) 
    p1.start () 
    P2 = MyProcess (3,4- ) 
    p2.start () 
    Print ( " main course: " , os.getpid ())

 

Second, open multiple word process, p.join () to use

join():

The main process code wait for the child to run end
p.join () above is performed asynchronously (subroutines), the following is performed synchronously (main) without p.join () are asynchronous
from multiprocessing import Process
import time
def test(name, i): print('%s is running' % name) time.sleep(i) print('%s is over' % name) if __name__ == '__main__': p_list = [] for i in range(3): p = Process(target=test,args=('进程%s'%i,i)) p.start () p_list.append (P) [p.join () for P in P_LIST]
   # = START_TIME the time.time ()
# P = Process (target = Test, args = ( 'Egon',. 1)) # Process = p1 (= the Test target, args = ( 'Kevin', 2)) # P2 = Process (target = the Test, args = ( 'Jason', 3)) # p.start () # just tells the operating system to help As this process you create a process when creating OS random decision # p1.start () # p2.start () # p2.join () # p.join () # p1.join () # main process code waits for the child process continues to run until the end of the run # p.join () # main process code wait for the child run ends Print ( ' primary ' ) print(time.time() - start_time)

Third, the isolation between processes and processes

  Between the process and the process is isolated from each other, are independent piece of memory space, do not share data
from multiprocessing import Process

money = 100


def test():
    global money
    money = 99999999


if __name__ == '__main__':
    p = Process(target=test)
    p.start()
    p.join()
    print(money) #100

 

 Fourth, the daemon

Daemons handle the process of change in the start () Add p.daemon above, the child process with the end of the primary process ends
DEF Test (name):
     the while True:
         Print ( ' % S manifold normally alive ' % name) 
        the time.sleep ( . 3 )
         Print ( ' % S manifold natural death ' % name) 


IF  the __name__ == ' __main__ ' : 
    P = Process (= the Test target, args = ( ' Egon ' ,)) 
    p.daemon = True   # the process of setting up the daemon is otherwise an error before this sentence must be placed start statement 
    p.start () 
    i = 0
     the whileI <10 : 
        the time.sleep ( 0.1 )
         Print ( ' the emperor jason life final sleep n ' ) 
        I + =. 1 # with the end of the main process is ended

Fifth, mutex

from multiprocessing import Process, Lock
import time
import json


# 查票
def search(i):
    with open('data', 'r', encoding='utf-8') as f:
        data = f.read()
    t_d = json.loads(data)
    print('用户%s查询余票为:%s' % (i, t_d.get('ticket')))


# 买票
def buy(i):
    with open('data', 'r', encoding='utf-8') as f:
        data = f.read()
    t_d = json.loads(data)
    time.sleep(1)
    if t_d.get('ticket') > 0:
        # 票数减一
        t_d['ticket'] -= 1
        # 更新票数
        with open('data', 'w', encoding=' ' ) AS F: 
            The json.dump (T_d, F) Print ( ' User grab votes success% s ' % I)
     the else :
         Print ( ' no ticket ' ) DEF RUN (I, the mutex): 
    Search (I) 
    the mutex .acquire ()   # grab the lock if someone else grabbed the lock must wait for the person to release the lock     Buy (i) 
    mutex.release ()   # release lock IF __name__ == ' __main__ ' : 
    mutex = lock ()   # generate a lock for I in Range (10utf-8
        






 
     ):
        p = Process(target=run, args=(i, mutex))
        p.start()

 

Guess you like

Origin www.cnblogs.com/wukai66/p/11330057.html