Python processes and threads

Process and thread:
*Process: Process is the basic unit of program execution and resource allocation in the system. Each process has its own data segment (stored data), code segment (stored code), stack segment (objects and variables). # Resources such as global variables cannot be shared among multiple processes. Modifying global variables in the child process has no effect on the global variables in the parent process.
*Thread: If you want to do multiple things at the same time in a process, you must run multiple " Subtasks", these subtasks are called threads; each thread shares all the resources (variables and data, etc.) and memory space of the process, so the variables of the process can be modified in the subthread.
*Multitasking: the operating system can simultaneously Run multiple tasks, each task is a process or a thread.
*Concurrency: Concurrency refers to a processor processing multiple tasks at the same time; because the cpu scheduling execution speed is too fast, it seems to be executed at the same time, in fact it is Alternately executed in turn.
*Parallel: Parallelism means that multiple processors process multiple tasks at the same time.
*The principle of single-core cpu to achieve multitasking: The operating system takes turns to execute each task alternately, because the cpu scheduling execution speed is too fast, It makes us feel as if all tasks are being executed at the same time.
*The principle of multi-core cpu to achieve multi-tasking: Since the actual number of tasks is much more than the number of cores of the cpu, the operating system will automatically schedule many tasks to each CPU in turn. Execute on each core.
* Ways to achieve multi-tasking: 1. Multi-process mode (used more): one parent process, n child processes, the processes are scheduled and executed by the operating system in no order; Then let the parent process end, you can use the .join() method at the end of the child process.
                                2. Multi-threading mode (used the most): one parent thread, n child threads, the threads are scheduled and executed by the operating system and there is no order. To execute the threads sequentially, you need to lock (Lock); To end the parent thread, you can use the .join() method at the end of the child thread.
                                3. Coroutine mode (seldom used): The coroutine looks like a subroutine, but during the execution process, it can be interrupted inside the subroutine, Then turn to execute other subprograms, not function calls.
                                4. Multi-process + multi-threading (generally not recommended)
*Multi-process module: multiprocessing, the Process class in it is used to create a process instance, Pool thread pool The class is used to create multiple process instances.
*Thread module: threading, the Thread class in it is used to create a thread instance, and the Lock class is used to create a lock instance.
*Computer IO operation: IO refers to It is the computer that performs read and write operations. Since the speed of the computer to perform read and write operations is much slower than the speed of cpu and memory, the underlying computer language such as C language, although the speed of cpu is much faster than python, sometimes still has to wait Computers perform IO operations, so python is competitive in some areas.

multi-Progress:

#Import the Process class from the multiprocessing module (multiprocessing)
 from multiprocessing import Process
 import time
 import os

#Define child process 
def run(str):
     while True:
         # os.getpid () gets the process id, os.getppid() gets the parent process id 
        print ( " process %s " % str,os.getpid(),os. getppid())
         # Delay 2 seconds 
        time.sleep(2 )


if  __name__ == ' __main__ ' :
     print ( "The parent process starts " ,os.getpid()) #Create
     a child process, use the Process class to create a pro object 
    pro = Process(target=run,args=( " 1 " ,) )
     #Start child process 
    pro.start()
     while True:
         print ( " process 2 " )
        time.sleep(2.5)

 

Thread lock:

#Application of thread lock, let threads execute sequentially. 
import time      #Import time module 
import threading     #Import threading thread module num = 10         
#Set a global variable 
lock = threading.Lock() #Create       a lock instance


def reduce_num(): #Set     a sub-thread function reduce_num 
    print ( " Sub-thread starts... " )
     global num         #Declare a global variable 
    lock.acquire() #Get     a lock object 
    temp = num         #Read a global variable num 
    num = temp - 1       #Decrease the variable taken from the global by one 
    lock.release() #Release       the lock 
    print ( " Sub thread ends...\n " )
    time.sleep( 1)      #Add a sleep function


if  __name__ == ' __main__ ' :
     print ( "The parent thread starts " )
     for i in range(10):     #loop from 0 to 10 
        t = threading.Thread(target=reduce_num) #Create       child threads in the loop, a total of Create 10 
        t.start()     #Start child threads in a loop 
        t.join() #After      the child thread ends, let the parent thread end

    print (" Result:%s" %num) #Print     the global variables that have been changed by multiple child thread functions. If the result is 0, the experiment is successful. 
    print ( "The parent thread ends " )

 Result: Result : 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325332590&siteId=291194637