Process, thread, coroutine? Use the story of One Piece to understand their differences

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only, and do not have any commercial use. If you have any questions, please contact us for processing.

The following article comes from the Python Life Chronicle, the author Python Life Chronicle

Python crawler, data analysis, website development and other case tutorial videos are free to watch online

https://space.bilibili.com/523606542 

Python learning exchange group: 1039645993

In the process of learning Python, one of the most direct feelings is that it is easy to get started, but it is difficult to master it. In many cases, it is inseparable from the basic knowledge of computer science. For example, for the following question, I cannot think of an accurate answer the first time.

  • What is the difference between a coroutine and a thread ?

On the road of learning, understanding and understanding is the input, and clearly speaking is the output. Only when you reach the step of output can you really understand a knowledge point. So, let’s tackle this problem first, and use One Piece’s story to understand the difference.

For coroutines and threads , I will add another process .

1 process

A process is an executing program. Each process has its own address space, memory, data stack, and other auxiliary data used to track execution. The operating system manages the execution of all processes on it and allocates time to these processes reasonably. Because each process has its own memory and data stack, etc., it can only use inter-process communication (IPC) to share information.

Process, intuitively speaking, after the program stored on the hard disk runs, an independent memory body will be formed in the memory space. This memory body has its own independent address space and its own heap. The upper-level affiliate is the operating system. The operating system will allocate system resources (CPU time slices, memory and other resources) based on the process as the unit, and the process is the smallest unit of resource allocation.

OK, here comes the Pirate show time.

It is said that Luffy and his party started from Novice Village, cutting the flag of the world government, breaking into the headquarters of the navy, destroying the seven martial arts, picking the four emperors, always fighting monsters and upgrading, and they have cultivated their skills and showed their domineering. Now I came to the country of Wano, and I was fighting against Kaido with my friends. At this time, the crusade against Kaido (The Kingdom of Japan) is a process in the world of One Piece , and its address space is Kaido's base camp-the country of Japan.

How can Kaido be destroyed? The crusade army needs to enter the enemy's territory first, then collect information lurking, then plot plans, and finally enter the enemy camp and cut off the head of Kaido. These are sub-processes of the entire crusade process . How the crusade army got the information, how the enemy sneaked into it, how Luffy fought, and how Zorro did it. . . These belong to the content of the process code segment . Kaido is not a vegetarian either. He took off from the ghost island and smashed into the city of flowers. The flight time of the ghost island should be the climax time of the whole plot. It is a global variable and belongs to the content of the process data segment . The straw hats here are fighting fiercely, and the world government, navy, and revolutionary army are not idle. Although the author has not explained it, they are also going on in the Pirate World. These constitute the multiple processes in One Pirate .

 

Example of the process module multiprocessing in python

# 进程代码
import os
from multiprocessing import Process


def fun_1(str):
    print("海贼王子进程id:", os.getpid(), str)


def main():
    p1 = Process(target=fun_1, args=('进程1:讨伐凯多',))
    p2 = Process(target=fun_1, args=('进程2:革命军在搞事',))
    p3 = Process(target=fun_1, args=('进程3:世界政府在观察',))

    p1.start()
    p2.start()
    p3.start()
    print('海贼王主进程id:', {os.getpid()})


if __name__ == '__main__':
    min()

Output results (different results for each run):

 

2 threads

Thread (thread) is the smallest unit that the operating system can perform operation scheduling. It is included in the process and is the actual operating unit in the process. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.

Threads are executed under the process and share the context, so the communication between threads under the same process is easier. Subroutines, or functions, are called hierarchical in all languages. For example, A calls B, B calls C during execution, C returns after execution, B returns after execution, and finally A is executed. So the subroutine call is realized through the stack, and a thread is to execute a subroutine. A subroutine call is always an entry, one return, and the calling sequence is clear. The call of a coroutine is different from a subroutine.

Okay, now we continue our pirate journey.

It is not an easy task to destroy Kaido. Kaido has a large number of people, and also forms an alliance with the aunt, and fights against it. How to fix them? Everyone got together and was just head-on. It is estimated that Luffy was exhausted before he touched Kaido, so in order to achieve his goal as soon as possible, each character has found his own opponent, king against king, general against general, and soldier against soldier , Everyone PK respectively. Luffy and Zorro pick Kaido and Auntie; Marko vs. Jhin and Quinn; Jinpei vs. Fosford; Frank vs. Sasaki. . . Each battle is to defeat the threads in the Kaido process, executed separately, without interfering with each other, and can be considered concurrent . In addition, there is a multi-threaded character in One Piece , which is the "gangster" Capone Becky. His ability to build the city's fruit directly allows him to easily defeat a hundred.

 

Example of multi-threaded code in python

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

if __name__ == "__main__":
    # 创建新线程
    thread1 = myThread(1, "线程1-路飞vs凯多", 1)
    thread2 = myThread(2, "线程2-甚平vs福斯福", 2)

    # 开启新线程
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print ("退出讨伐凯多主线程")

The output result is:

 

3 Coroutine

Coroutine  (coroutine), also known as micro-threading, it is another way to multi-task, but is smaller than the thread execution unit. Because it comes with the context of the CPU, so as long as the right time, we can switch from one coroutine to another.

In a function in a thread, we can save some temporary variables and other information of the current function anywhere, and then switch to another function for execution. Note that it is not done by calling the function, and the number of switching and It is up to the developer to determine when to switch to the original function.

Finally, our real man, Sanji, came out to show off.

The standard equipment of suits and cigarettes, this is our gentleman-Sanji, a man who kicks out a world with a pair of feet. However, the realization in the Wano Country chapter is still not brilliant. When facing the Black Maria, he is interrupted and unable to display his strength. Sanji can only send a distress signal to Robin. As soon as Robin received the signal, Yield knew. In the whole process, Sanji was executing distress signals until the number of signals reached a threshold and Robin appeared.

 

Understanding of coroutine code in python

def luobin():
    r = ''
    while True:
        n = yield r
        if not n:
            return
        if n == 5:
            print("[罗宾] 我听到第 %s 次求救了,我到了" % n)
        else:
            print('[罗宾] 我听到第 %s 次求救了,马上来' % n)
            r = '知道了,马上'

def shanzhi(c):
    c.send(None)
    n = 0
    while n < 5:
        n = n + 1
        print('[山治] 第 %s 次求救:罗宾快来救我' % n)
        r = c.send(n)
        if n == 5:
            print('[山治] 罗宾你来了!')
        else:
            print('[山治] 罗宾回答: %s' % r)
    c.close()

c = luobin()
shanzhi(c)

The output result is:

[山治] 第 1 次求救:罗宾快来救我
[罗宾] 我听到第 1 次求救了,马上来
[山治] 罗宾回答: 知道了,马上
[山治] 第 2 次求救:罗宾快来救我
[罗宾] 我听到第 2 次求救了,马上来
[山治] 罗宾回答: 知道了,马上
[山治] 第 3 次求救:罗宾快来救我
[罗宾] 我听到第 3 次求救了,马上来
[山治] 罗宾回答: 知道了,马上
[山治] 第 4 次求救:罗宾快来救我
[罗宾] 我听到第 4 次求救了,马上来
[山治] 罗宾回答: 知道了,马上
[山治] 第 5 次求救:罗宾快来救我
[罗宾] 我听到第 5 次求救了,我到了

Guess you like

Origin blog.csdn.net/m0_48405781/article/details/114697212