Python: process operations in python programs, python program process operations

Source: Internet
Author: User

Python: process operations in python programs, python program process operations

I. multi-process application

import socketfrom multiprocessing import Processdef talk(conn):    conn.send(b'connected')    ret = conn.recv(1024)    print(ret)if __name__ == '__main__':    sk = socket.socket()    sk.bind(('127.0.0.1', 8080))    sk.listen()    while True:        conn,addr = sk.accept()        p = Process(target=talk,args=(conn,))        p.start()    conn.close()    sk.close()
Server
import socketsk = socket.socket()sk.connect(('127.0.0.1',8080))ret = sk.recv(1024)print(ret)msg = input('>>>')sk.send(msg.encode('utf-8'))sk.close()
Client

2. Other methods in the process

Import timefrom multiprocessing import Processdef func (): print ('--' * 10) time. sleep (15) print ('--' * 10) def cal_time (): while True: time. sleep (1) print ('past 1 second ') if _ name _ =' _ main _ ': p = Process (target = cal_time) p. daemon = True # daemon process: You must set p. start () p2 = Process (target = func) #15 s p2.start () for I in range (100): #10 s time. sleep (0.1) print ('* I) p2.join ()

1. start () starts a process.

Join: Using join allows the main process to wait until the child process ends.

1) p. daemon = True # daemon

The daemon process ends with the code execution of the main process.

When a normal sub-process is not completed, the main process will be waiting.

2) functions of daemon

It will end with the execution of the main process code and will not wait for other sub-Processes

3) Note:

The daemon must be set between start and start.

Sub-processes cannot be started in the daemon.

2, is_alive and terminate

import timefrom multiprocessing import Processdef func():    print('wahaha')    time.sleep(5)    print('qqxing')if __name__ == '__main__':    p = Process(target=func)    p.start()    print(p.is_alive())      time.sleep(0.1)    p.terminate()            print(p.is_alive())      time.sleep(1)    print(p.is_alive())
P. is_alive () # True indicates that the process is still False, indicating that the process is not there
P. terminate () # terminate a process, but this process will not be killed immediately
Def func (): print ('wahahaha') time. sleep (5) print ('qqx') if _ name _ = '_ main _': p = Process (target = func) p. start () print (p. name, p. pid) p. name = 'Wow Haha 'print (p. name) class MyProcess (Process): def run (self): print ('wahahaha', self. name, self. pid) time. sleep (5) print ('qqx', self. name, self. pid) if _ name _ = '_ main _': p = MyProcess () p. start () print (p. pid) # pid view the process id # name view the process name

Iii. Lock

From multiprocessing import Lock # Call lock Lock = lock () # create a Lock lock. acquire () # lock the key. acquire () # block lock to lock. release () # release the lock and return the key
The lock ensures data security in concurrent programming.
Import jsonimport timeimport randomfrom multiprocessing import Lockfrom multiprocessing import Processdef search (I): with open ('ticket ') as f: print (I, json. load (f) ['Count']) def get (I): with open ('ticket') as f: ticket_num = json. load (f) ['Count'] time. sleep (random. random () if ticket_num> 0: with open ('ticket', 'w') as f: json. dump ({'Count': ticket_num-1}, f) print ('% s bought' % I) else: print ('% s no votes' % I) def task (I, lock): search (I) # view the ticket lock. acquire () get (I) # lock the ticket. release () if _ name _ = '_ main _': lock = Lock () for I in range (20 ): #20 people grab tickets at the same time p = Process (target = task, args = (I, lock) p. start () import jsonimport timeimport randomfrom multiprocessing import Lockfrom multiprocessing import Processdef search (I): with open ('ticket ') as f: print (I, json. load (f) ['Count']) def get (I): with open ('ticket') as f: ticket_num = json. load (f) ['Count'] time. sleep (random. random () if ticket_num> 0: with open ('ticket', 'w') as f: json. dump ({'Count': ticket_num-1}, f) print ('% s bought' % I) else: print ('% s no votes' % I) def task (I, lock): search (I) # view the ticket lock. acquire () get (I) # lock the ticket. release () if _ name _ = '_ main _': lock = Lock () for I in range (20 ): #20 people grab tickets at the same time p = Process (target = task, args = (I, lock) p. start ()
Procedures for buying train tickets

4. semaphores

Import timeimport randomfrom multiprocessing import Semaphore # Call semaphores from multiprocessing import Processdef sing (I, sem): sem. acquire () print ('% s: Enter ktv' % I) time. sleep (random. randint () print ('% s: Exit ktv' % I) sem. release () #20 people in mini CHANGBA. At the same time, only four people can sing in. if _ name _ = '_ main _': sem = Semaphore (4) for I in range (20): Process (target = sing, args = (I, sem )). start () # The number of semaphores is the number of keys in the lock.

5. Events

Event-asynchronous Blocking
Events are all processes and are congested.
From multiprocessing import Event # Call Event Module # e = Event () # instantiate an Event sign/similar to a traffic signal # e. set () # Turn the sign into non-blocking/similar to turning the traffic light green # e. wait () # An event object just instantiated. The default signal is the blocking signal/the default signal is the red light # Run it on wait. Check the light first, and the green light stops at the red light, if the light turns green during the stop process, # It turns into non-blocking # e. clear () # Turn the sign into a blocking/the traffic light turns red # e. is_set () # block or not. True indicates the green light. False indicates the red light.
Import timeimport randomfrom multiprocessing import Processfrom multiprocessing import Eventdef traffic_light (e): while True: if e. is_set (): time. sleep (3) print ('red light ') e. clear () # green to red else: time. sleep (3) print ('green light ') e. set () # red to green def car (I, e): e. wait () print ('% s vehicle pass' % I) if _ name _ = '_ main _': e = Event () # Set a red light tra = Process (target = traffic_light, args = (e,) tra. start () # start a process to control the traffic light for I in range (100): if I % 6 = 0: time. sleep (random. randint (1, 3) car_pro = Process (target = car, args = (I, e) car_pro.start ()

6. Queue

Communication between queue Processes
1. the multiprocessing Queue module can be used for inter-process communication.
2. There are two ways to create a queue. The first is to create a queue with maximum length without passing parameters.
3. Two important methods are provided. put get
4. qsize view queue size
Import timedef producer (q): # producer for I in range (100): q. put ('steamed stuffed bun % s' % I) def consumer (q): # consumer for I in range (100): time. sleep (1) print (q. get () if _ name _ = '_ main _': q = Queue (10) # tray p = Process (target = producer, args = (q,) p. start () c1 = Process (target = consumer, args = (q,) c2 = Process (target = consumer, args = (q,) c1.start () c2.start ()

 

Related Article

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.