Network programming: Processes

Network programming: Processes

  • UDP coding (just understand)

  • Computer core theory (development history)

  • Process theory

  • Many ways to start the process

  • Process join method

  • Interprocess data isolation

  • IPC mechanism

UDP coding

  • UDP is suitable for occasions that require relatively high efficiency and relatively low accuracy, such as video on demand, network voice call and so on.
  • The methods often used for UDP programming in socket module mainly include:
  • socket([family[,type[,proto]]]): create a socket object, where family is socket AF_ INET means IPV4, socket AF_ Inet6 indicates IPV6; Type is SOCK_STREAM means TCP protocol, SOCK_DGRAM represents UDP protocol.
  • sendto(string,address): send the byte string specified by string to the address specified by address. Address is a tuple in the format of (IP address, port number)
  • recvfrom(bufsize[,flags]): receive data

Case:

import socket
udp_sk = socket.socket(type=socket.SOCK_DGRAM)  # UDP protocol
udp_sk.bind(('127.0.0.1',9000))  # Binding address
msg,addr = udp_sk.recvfrom(1024)
udp_sk.sendto(b'hi',addr)             
udp_sk.close() 


import socket
ip_port=('127.0.0.1',9000)
udp_sk=socket.socket(type=socket.SOCK_DGRAM)
udp_sk.sendto(b'hello',ip_port)
back_msg,addr=udp_sk.recvfrom(1024)
print(back_msg.decode('utf-8'),addr)

Implementation principle of time server: 1 Internal small capacitor power supply, 2 Remote time synchronization

History of operating system

Learning concurrent programming is learning the history of the operating system

1. The era of punched cards

cpu utilization polar

2. Online batch processing system

The programs of multiple programmers are input into the tape at one time, and then input by the input machine and executed by the cpu

3. Offline batch processing system

Prototype of modern computer (remote input high-speed tape host)

Multichannel technology

Premise: single core CPU, multi-channel technology, switching + save state

CPU working mechanism: 1 When a program enters the io state, the operating system will automatically deprive the CPU execution permission of the program

                          2. When a program occupies CPU for a long time, the operating system will also deprive the CPU execution permission of the program

Parallelism and Concurrency: parallelism: multiple programs execute simultaneously

Concurrency: multiple programs can run as long as they look like they are running at the same time

ps: single core CPU can't parallel events, but can achieve concurrency

Process theory

The difference between process and program: Program: a pile of code

Processes: running programs

Process regulation in the case of single core: evolution of process scheduling algorithm

                                         1.FCFS # first come, first served

Unfriendly to multiple operations

                                          2. Short job first scheduling algorithm

Unfriendly to long homework

                                          3. Time slice rotation method + multi-level feedback queue

First assign the same time slice to new multiple processes

After that, it is divided into categories according to the time slice consumed by the process

Process three state diagram: ready state, running state, blocking state

The process must go through the ready state before entering the running state

Synchronous and asynchronous: used to describe the task submission method

Synchronization: after submitting a task, do nothing while waiting for the return result of the task

Asynchronous: after submitting a task, do not wait for the return result of the task, and directly do other things. The result is automatically reminded by a feedback mechanism

Blocking and non blocking: used to describe the execution status of a task

Blocking: blocking state

Non blocking: ready and running

Create process

Code level creation process

from multiprocessing import Process
import time
import os


def test(name):
    print(os.getpid())  # Get process number
    print(os.getppid())  # Get parent process number
    print('%s Running' % name)
    time.sleep(3)
    print('%s It's already over.' % name)


if __name__ == '__main__':
    p = Process(target=test, args=('jason',))  # Generate a process object
    p.start()  # Tell the operating system to open a new process asynchronous submission
    print(os.getpid())
    print('main')

Setting up a process in windows is similar to importing a module. It is necessary to execute the code again from top to bottom_ main_ The code that executes the process in the judgment statement

In linux, a complete copy of the code is directly executed without_ main_ Execute within judgment statement

class MyProcess(Process):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def run(self):
        print('%s Running' % self.name)
        time.sleep(3)
        print('%s It's already over.' % self.name)

if __name__ == '__main__':
    p = MyProcess('jason')
    p.start()
    print('main')

join method of process

from multiprocessing import Process
import time


def test(name, n):
    print('%s is running' % name)
    time.sleep(n)
    print('%s is over' % name)


if __name__ == '__main__':
    p_list = []
    start_time = time.time()
    for i in range(1, 4):
        p = Process(target=test, args=(i, i))
        p.start()
        p_list.append(p)
        # p.join()  # Serial 9s+
    for p in p_list:
        p.join()
    print(time.time() - start_time)

    # p = Process(target=test, args=('jason',))
    # p1 = Process(target=test, args=('kevin',))
    # p2 = Process(target=test, args=('oscar',))
    # p.start()
    # p1.start()
    # p2.start()
    print('Main process')

No interaction between processes by default

Data between processes is isolated from each other

from multiprocessing import Process

money = 100


def test():
    global money
    money = 999


if __name__ == '__main__':
    p = Process(target=test)
    p.start()
    # Make sure the subprocess is running before printing
    p.join()
    print(money)

Object method

1.current_process view process number

2.os.getpid () view the process number OS. getppid() view the parent process number

3. The process name, p.name, is available by default. You can also pass in name = '' in the form of keyword when instantiating the process object

4.p.is_alive() determines whether the process is alive. 3,4 the result cannot be seen in combination because the operating system needs reaction time. The effect can be seen when the main process sleeps 0.1

 

Added by press711 on Thu, 13 Jan 2022 14:14:49 +0200