Python basis - multithreading (on)

The previous process a little knowledge, popular understanding, the process is the operating system (OS) for resource scheduling allocation basic unit, at least on a process to be "monitored" in the OS each program with Oh. Then around the multi-process, shared global variables with the message queue, the guardian of the main process, through this process pool ... explore, of course, lopsided application, local processing of multiple tasks occasionally work myself, but also a priority to get multiple processes (mainly company computer thief strong, I'm going to get a multi-process, it is necessary waste of resources haha ..).

Process it, basically never used, (except reptiles, before scrapy is useful for multi-threaded), to their own handwriting should not. Why would prefer to give priority to process it, because most of us use the Python interpreter is CPython . It By default, in fact, we have set up blocking , and one, in fact CPython not really able to achieve in a multi-threaded multi-threaded .. I will not speak ...

But also from the perspective of popular understand the words, a process (program), there is at least one process of processes and threads, it can be seen as a 1: n relationship.

OS scheduling, multiple processes, each with multiple threads. Understood that "quantity" relationship should be.

Single-threaded

, A piece of code that is executed in order from the perspective of the code, is a a single process.

import time


# 我每天下班之后首先是: 煮饭, 做菜
def cook_rice():
    for i in range(3):
        print(f"cook rice ...{i}")
        time.sleep(1)


def cook_dishes():
    for i in range(4):
        print(f"cook dishes...{i}")
        time.sleep(0.5)


if __name__ == '__main__':
    cook_rice()
    cook_dishes()
cook rice ...0
cook rice ...1
cook rice ...2
cook dishes...0
cook dishes...1
cook dishes...2
cook dishes...3

This is the result we want with no problems. First cook, then cook ... but, truth is this thing? Truth is I first plugged in rice, then turn on the computer, put on some music what, I set out to vegetables, vegetable these things .

Visible really is that cooking for this program, I can actually be done at the same time. It is also multi-task previously mentioned it, from the point of view of life, this is a very natural thing. And I always point is that writing code in essence, the abstract world of reality and simulation . Therefore, the vegetables to cook basic things that have to face every day, in the same program from, nature is classified as a Python basis.

Multithreading

Thread class also with a built-in Python threading module, to demonstrate wave oh, cooking and cooking can get together.

import time
import threading


# 我每天下班之后首先是: 煮饭, 做菜
def cook_rice():
    for i in range(3):
        print(f"cook rice ...{i}")
        time.sleep(1)


def cook_dishes():
    for i in range(4):
        print(f"cook dishes...{i}")
        time.sleep(0.5)


if __name__ == '__main__':

    # 假设就各创一个线程来弄
    t1 = threading.Thread(target=cook_rice)
    t2 = threading.Thread(target=cook_dishes)

    # 启动多线程
    t1.start()
    t2.start()
cook rice ...0
cook dishes...0
cook dishes...1
cook rice ...1
cook dishes...2
cook dishes...3
cook rice ...2

You can see the process is continued in "Switch" with the term process that multiple processes of making "task scheduler" thread here, you, ah, multiple threads to run with it. (In fact, not really multiple threads run, but scheduling just too fast cpu).

The main thread - wait for all child threads

With multi-process is the same, the main thread will wait for all child processes by default, after the end of all, the program will really end.

Then create a thread, mass participation is the same, in two ways * args and ** kwargs. These are nothing, roughly impression on the line, and the process is more important characteristics, how to write, Baidu would like to understand.

import time
import threading


# 我每天下班之后首先是: 煮饭, 做菜
def cook_rice(n):
    for i in range(n):
        print(f"cook rice ...{i}")
        time.sleep(1)


def cook_dishes(n):
    for i in range(n):
        print(f"cook dishes...{i}")
        time.sleep(0.5)


if __name__ == '__main__':

    # 假设就各创一个线程来弄
    t1 = threading.Thread(target=cook_rice, args=(3,))
    t2 = threading.Thread(target=cook_dishes, kwargs={"n":4})

    # 启动多线程
    t1.start()
    t2.start()

    print("main threading done ....")
cook rice ...0
cook dishes...0
main threading done ....
cook dishes...1
cook rice ...1
cook dishes...2
cook dishes...3
cook rice ...2

Guard the main thread

But also with the process of the same piece, from the code perspective, that is, to set a property, daemon = True to.

import time
import threading


def cook_rice(n):
    for i in range(n):
        print(f"cook rice ...{i}")
        time.sleep(1)


if __name__ == '__main__':

    # 将 daemon 参数 传为 True 即设置为了守护主线程.
    t1 = threading.Thread(target=cook_rice, args=(4,), daemon=True)

    # 启动多线程
    t1.start()
    time.sleep(2)
    print("main threading done ....")
cook rice ...0
cook rice ...1
cook rice ...2
main threading done ....

In my tests, this part of discovery threads and processes have a different point, in multiple threads, if only one thread to the daemon, when the end of the primary process, the rest of the thread will continue to execute; and in more than a process, if a process which will give daemon, stopped the entire mission will follow. very strange, not yet arrived at that point, temporarily, and then I follow Cece see.

Obstruction - ending wait for the child

In fact, this puzzling, do not run directly set the daemon is not on line yet, mainly what, I simply want to become familiar with join () This API just friends.

import time
import threading


# 我每天下班之后首先是: 煮饭, 做菜
def cook_rice(n):
    for i in range(n):
        print(f"cook rice ...{i}")
        time.sleep(1)


if __name__ == '__main__':
    # 假设就各创一个线程来弄
    t1 = threading.Thread(target=cook_rice, args=(4,), daemon=True)

    # 启动多线程
    t1.start()
    time.sleep(2)

    # 阻塞等待, 子进程结束
    t1.join()
    print("main threading done ....")
cook rice ...0
cook rice ...1
cook rice ...2
cook rice ...3
main threading done ....

Guess you like

Origin www.cnblogs.com/chenjieyouge/p/12393106.html