Help you understand Python processes, threads and collaborations

This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/4425/ In the operating system, every program that runs independently occupies the resources allocated by the operating system. These programs do not interfere with each other and only run their own program code, which is the process.

However, when the operating system frequently creates the destruction process, a large number of system resources are wasted in the process of creation and destruction. With the emergence of multi-core cpu, threads have gradually replaced processes, and become the basic unit of operating system that can run independently.

When a process is not a multithreaded program, the only thread in the process is the code block that the process itself runs.

When multiple threads appear in a process, multiple threads share the resources of the process and accept the scheduling of the operating system to run each thread.

state

Association

To understand the concept of orchestration, let's first look at concurrency and parallelism.

parallel

Parallel is easy to understand, that is, there are multiple programs executing at the same time. The program here refers to the thread of the operating system.

Each cpu core can only run a set of instructions at the same time, which means that at the same time, there is only one thread executing on a core.

When the cpu has four cores, it can only execute four threads.

Concurrent

To understand concurrency, you need to know and.

Synchronous block

When an I/O operation in a program takes a long time, the program is not suspended, and has been waiting for network data transmission, unable to perform other operations, this is synchronous blocking.

One concept of synchronization is that after the network transmission is completed, the main program cannot be informed that the operation is completed, which leads to the main program:

  • Or you can only wait for I/O to complete
  • Or poll to see if the transmission is complete

Of course, other operations can be performed during polling. At this time, it is in the non blocking state, that is, synchronous non blocking.

Synchronous non blocking

The concept of non blocking is that the main program can perform other operations.

Asynchronous blocking

If there is synchronization, there is asynchrony.

Asynchronous blocking and synchronous blocking are the same. The main program does nothing and waits for the I/O operation to complete.

Asynchronous non blocking

Asynchronous non blocking state is the key to concurrency.

When the main program uses asynchronous I/O operation, it will not affect the subsequent operation of the main program. When the asynchronous I/O operation is completed, it will actively notify the main program to perform other operations, so as to reduce the resource consumption in the polling process and focus on other work.

Concurrent

Concurrency is a form of asynchronous non blocking state. When a program executes operation a, it makes the I/O of a asynchronous operation. At this time, the program executes operation b. externally, a and b are executed at the same time, but they only run in one thread.

Different from threads and processes, a cooperation program is not a program in the physical level of the operating system.

The process is program level, and the programmer controls the whole process life cycle. In this way, it can achieve the same effect as operating system multithreading, but it can save the resource consumption caused by off the shelf switching.

By using programs to manipulate the process, the cpu is running all the time, and it is the illusion that multiple processes are running all the time, which also becomes concurrency.

Example

Let's illustrate the relationship among processes, threads and coroutines in python with several examples.

Process instance

How do we write multiprocess programs in python?

The answer is to use the module multiprocessing for implementation.

import time  
from multiprocessing import Process  
  
class Test(Process):  
    def __init__(self):  
        super().__init__()  
      
    def run(self):  
        while True:  
            print("process b is run")  
            time.sleep(1)

By inheriting the multiprocessing Process, implementing the Process class, and then implementing the run method, you can realize the content of the Process to run in this method.

from process_b import Test  
import time  
  
if __name__ == "__main__":  
    t = Test()  
    t.start()  
    while True:  
        print("process a run")  
        time.sleep(1)

The calling method is also very simple, directly using Test to instantiate the object, then calling the member function start() of the object.

python3 process_a.py  
process a run  
process b is run  
process b is run  
process a run  
process a run  
process b is run  
process b is run  
process a run

Thread instance

Because GIL exists in Cpython, multithreading will also become a thread on a single core cpu in practical application and run in queue.

import threading  
import time  
  
class ThreadTest (threading.Thread):  
    def __init__(self, name):  
        super().__init__()  
        self.name = name  
  
    def run(self):  
        while True:  
            print(f"i am in thread {self.name}")  
            time.sleep(1)  
  
  
if __name__ == "__main__":  
    threads = []  
    for i in range(4):  
        t = ThreadTest(i)  
        threads.append(t)  
      
    for t in threads:  
        t.start()  
      
    for t in threads:  
        t.join()

The thread class is implemented by inheriting threading.Thread, and then the object is generated by instantiation, and the thread can be started by calling the start() of the object.

Operation result

python3 thread_a.py  
i am in thread 0  
i am in thread 1  
i am in thread 2  
i am in thread 3  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1

Association

Python 3 adds asyncio to the standard library.

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

Operation result

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

summary

The above is all the content of this section. It mainly introduces the concepts and examples of processes, threads and coroutines. This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/4425/ In the operating system, every program that runs independently occupies the resources allocated by the operating system. These programs do not interfere with each other and only run their own program code, which is the process.

However, when the operating system frequently creates the destruction process, a large number of system resources are wasted in the process of creation and destruction. With the emergence of multi-core cpu, threads have gradually replaced the process and become the basic unit of the operating system that can run independently.

When a process is not a multithreaded program, the only thread in the process is the code block that the process itself runs.

When multiple threads appear in a process, multiple threads share the resources of the process and accept the scheduling of the operating system to run each thread.

state

Association

To understand the concept of orchestration, let's first look at concurrency and parallelism.

parallel

Parallel is easy to understand, that is, there are multiple programs executing at the same time. The program here refers to the thread of the operating system.

Each cpu core can only run a set of instructions at the same time, which means that at the same time, there is only one thread executing on a core.

When the cpu has four cores, it can only execute four threads.

Concurrent

To understand concurrency, you need to know and.

Synchronous block

When an I/O operation in a program takes a long time, the program is not suspended, and has been waiting for network data transmission, unable to perform other operations, this is synchronous blocking.

One concept of synchronization is that after the network transmission is completed, the main program cannot be informed of the completion of the operation, which results in the main program:

  • Or you can only wait for I/O to complete
  • Or poll to see if the transmission is complete

Of course, other operations can be performed during polling. At this time, it is in the non blocking state, that is, synchronous non blocking.

Synchronous non blocking

The concept of non blocking means that the main program can perform other operations.

Asynchronous blocking

If there is synchronization, there is asynchrony.

Asynchronous blocking and synchronous blocking are the same. The main program does nothing and waits for the I/O operation to complete.

Asynchronous non blocking

Asynchronous non blocking state is the key to concurrency.

When the main program uses asynchronous I/O operation, it will not affect the subsequent operation of the main program. When the asynchronous I/O operation is completed, it will actively notify the main program to perform other operations, so as to reduce the resource consumption in the polling process and focus on other work.

Concurrent

Concurrency is a form of asynchronous non blocking state. When a program executes operation a, it makes the I/O of a asynchronous operation. At this time, the program executes operation b. externally, a and b are executed at the same time, but they only run in one thread.

Different from threads and processes, a cooperation program is not a program in the physical level of the operating system.

The process is program level, and the programmer controls the whole process life cycle. In this way, it can achieve the same effect as operating system multithreading, but it can save the resource consumption caused by off the shelf switching.

By using programs to manipulate the process, the cpu is running all the time, and it is the illusion that multiple processes are running all the time, which also becomes concurrency.

Example

Let's illustrate the relationship among processes, threads and coroutines in python with several examples.

Process instance

How do we write multiprocess programs in python?

The answer is to use the module multiprocessing for implementation.

import time  
from multiprocessing import Process  
  
class Test(Process):  
    def __init__(self):  
        super().__init__()  
      
    def run(self):  
        while True:  
            print("process b is run")  
            time.sleep(1)

By inheriting the multiprocessing Process, implementing the Process class, and then implementing the run method, you can realize the content of the Process to run in this method.

from process_b import Test  
import time  
  
if __name__ == "__main__":  
    t = Test()  
    t.start()  
    while True:  
        print("process a run")  
        time.sleep(1)

The calling method is also very simple, directly using Test to instantiate the object, then calling the member function start() of the object.

python3 process_a.py  
process a run  
process b is run  
process b is run  
process a run  
process a run  
process b is run  
process b is run  
process a run

Thread instance

Because GIL exists in Cpython, multithreading will also become a thread on a single core cpu in practical application and run in queue.

import threading  
import time  
  
class ThreadTest (threading.Thread):  
    def __init__(self, name):  
        super().__init__()  
        self.name = name  
  
    def run(self):  
        while True:  
            print(f"i am in thread {self.name}")  
            time.sleep(1)  
  
  
if __name__ == "__main__":  
    threads = []  
    for i in range(4):  
        t = ThreadTest(i)  
        threads.append(t)  
      
    for t in threads:  
        t.start()  
      
    for t in threads:  
        t.join()

The thread class is implemented by inheriting threading.Thread, and then the object is generated by instantiation, and the thread can be started by calling the start() of the object.

Operation result

python3 thread_a.py  
i am in thread 0  
i am in thread 1  
i am in thread 2  
i am in thread 3  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1

Association

Python 3 adds asyncio to the standard library.

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

Operation result

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

summary

The above is all the content of this section. It mainly introduces the concepts and examples of processes, threads and coroutines. This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/4425/ In the operating system, every program that runs independently occupies the resources allocated by the operating system. These programs do not interfere with each other and only run their own program code, which is the process.

However, when the operating system frequently creates the destruction process, a large number of system resources are wasted in the process of creation and destruction. With the emergence of multi-core cpu, threads have gradually replaced the process and become the basic unit of the operating system that can run independently.

When a process is not a multithreaded program, the only thread in the process is the code block that the process itself runs.

When multiple threads appear in a process, multiple threads share the resources of the process and accept the scheduling of the operating system to run each thread.

state

Association

To understand the concept of orchestration, let's first look at concurrency and parallelism.

parallel

Parallel is easy to understand, that is, there are multiple programs executing at the same time. The program here refers to the thread of the operating system.

Each cpu core can only run a set of instructions at the same time, which means that at the same time, there is only one thread executing on a core.

When the cpu has four cores, it can only execute four threads.

Concurrent

To understand concurrency, you need to know and.

Synchronous block

When an I/O operation in a program takes a long time, the program is not suspended, and has been waiting for network data transmission, unable to perform other operations, this is synchronous blocking.

One concept of synchronization is that after the network transmission is completed, the main program cannot be informed that the operation is completed, which leads to the main program:

  • Or you can only wait for I/O to complete
  • Or poll to see if the transmission is complete

Of course, other operations can be performed during polling. At this time, it is in the non blocking state, that is, synchronous non blocking.

Synchronous non blocking

The concept of non blocking means that the main program can perform other operations.

Asynchronous blocking

If there is synchronization, there is asynchrony.

Asynchronous blocking and synchronous blocking are the same. The main program does nothing and waits for the I/O operation to complete.

Asynchronous non blocking

Asynchronous non blocking state is the key to concurrency.

When the main program uses asynchronous I/O operation, it will not affect the subsequent operation of the main program. When the asynchronous I/O operation is completed, it will actively notify the main program to perform other operations, so as to reduce the resource consumption in the polling process and focus on other work.

Concurrent

Concurrency is a form of asynchronous non blocking state. When a program executes operation a, it makes the I/O of a asynchronous operation. At this time, the program executes operation b. externally, a and b are executed at the same time, but they only run in one thread.

Different from threads and processes, a cooperation program is not a program in the physical level of the operating system.

The process is program level, and the programmer controls the whole process life cycle. In this way, it can achieve the same effect as operating system multithreading, but it can save the resource consumption caused by off the shelf switching.

By using programs to manipulate the process, the cpu is running all the time, and it is the illusion that multiple processes are running all the time, which also becomes concurrency.

Example

Let's illustrate the relationship among processes, threads and coroutines in python with several examples.

Process instance

How do we write multiprocess programs in python?

The answer is to use the module multiprocessing for implementation.

import time  
from multiprocessing import Process  
  
class Test(Process):  
    def __init__(self):  
        super().__init__()  
      
    def run(self):  
        while True:  
            print("process b is run")  
            time.sleep(1)

By inheriting the multiprocessing Process, implementing the Process class, and then implementing the run method, you can realize the content of the Process to run in this method.

from process_b import Test  
import time  
  
if __name__ == "__main__":  
    t = Test()  
    t.start()  
    while True:  
        print("process a run")  
        time.sleep(1)

The calling method is also very simple, directly using Test to instantiate the object, then calling the member function start() of the object.

python3 process_a.py  
process a run  
process b is run  
process b is run  
process a run  
process a run  
process b is run  
process b is run  
process a run

Thread instance

Because GIL exists in Cpython, multithreading will also become a thread on a single core cpu in practical application and run in queue.

import threading  
import time  
  
class ThreadTest (threading.Thread):  
    def __init__(self, name):  
        super().__init__()  
        self.name = name  
  
    def run(self):  
        while True:  
            print(f"i am in thread {self.name}")  
            time.sleep(1)  
  
  
if __name__ == "__main__":  
    threads = []  
    for i in range(4):  
        t = ThreadTest(i)  
        threads.append(t)  
      
    for t in threads:  
        t.start()  
      
    for t in threads:  
        t.join()

The thread class is implemented by inheriting threading.Thread, and then the object is generated by instantiation, and the thread can be started by calling the start() of the object.

Operation result

python3 thread_a.py  
i am in thread 0  
i am in thread 1  
i am in thread 2  
i am in thread 3  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1

Association

Python 3 adds asyncio to the standard library.

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

Operation result

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

summary

The above is all the content of this section. It mainly introduces the concepts and examples of processes, threads and coroutines. This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/4425/ In the operating system, every program that runs independently occupies the resources allocated by the operating system. These programs do not interfere with each other and only run their own program code, which is the process.

However, when the operating system frequently creates the destruction process, a large number of system resources are wasted in the process of creation and destruction. With the emergence of multi-core cpu, threads have gradually replaced the process and become the basic unit of the operating system that can run independently.

When a process is not a multithreaded program, the only thread in the process is the code block that the process itself runs.

When multiple threads appear in a process, multiple threads share the resources of the process and accept the scheduling of the operating system to run each thread.

state

Association

To understand the concept of orchestration, let's first look at concurrency and parallelism.

parallel

Parallel is easy to understand, that is, there are multiple programs executing at the same time. The program here refers to the thread of the operating system.

Each cpu core can only run a set of instructions at the same time, which means that at the same time, there is only one thread executing on a core.

When the cpu has four cores, it can only execute four threads.

Concurrent

To understand concurrency, you need to know and.

Synchronous block

When an I/O operation in a program takes a long time, the program is not suspended, and has been waiting for network data transmission, unable to perform other operations, this is synchronous blocking.

One concept of synchronization is that after the network transmission is completed, the main program cannot be informed that the operation is completed, which leads to the main program:

  • Or you can only wait for I/O to complete
  • Or poll to see if the transmission is complete

Of course, other operations can be performed during polling. At this time, it is in the non blocking state, that is, synchronous non blocking.

Synchronous non blocking

The concept of non blocking means that the main program can perform other operations.

Asynchronous blocking

If there is synchronization, there is asynchrony.

Asynchronous blocking and synchronous blocking are the same. The main program does nothing and waits for the I/O operation to complete.

Asynchronous non blocking

Asynchronous non blocking state is the key to concurrency.

When the main program uses asynchronous I/O operation, it will not affect the subsequent operation of the main program. When the asynchronous I/O operation is completed, it will actively notify the main program to perform other operations, so as to reduce the resource consumption in the polling process and focus on other work.

Concurrent

Concurrency is a form of asynchronous non blocking state. When a program executes operation a, it makes the I/O of a asynchronous operation. At this time, the program executes operation b. externally, a and b are executed at the same time, but they only run in one thread.

Different from threads and processes, a cooperation program is not a program in the physical level of the operating system.

The process is program level, and the programmer controls the whole process life cycle. In this way, it can achieve the same effect as operating system multithreading, but it can save the resource consumption caused by off the shelf switching.

By using programs to manipulate the process, the cpu is running all the time, and it is the illusion that multiple processes are running all the time, which also becomes concurrency.

Example

Let's illustrate the relationship among processes, threads and coroutines in python with several examples.

Process instance

How do we write multiprocess programs in python?

The answer is to use the module multiprocessing for implementation.

import time  
from multiprocessing import Process  
  
class Test(Process):  
    def __init__(self):  
        super().__init__()  
      
    def run(self):  
        while True:  
            print("process b is run")  
            time.sleep(1)

By inheriting the multiprocessing Process, implementing the Process class, and then implementing the run method, you can realize the content of the Process to run in this method.

from process_b import Test  
import time  
  
if __name__ == "__main__":  
    t = Test()  
    t.start()  
    while True:  
        print("process a run")  
        time.sleep(1)

The calling method is also very simple, directly using Test to instantiate the object, then calling the member function start() of the object.

python3 process_a.py  
process a run  
process b is run  
process b is run  
process a run  
process a run  
process b is run  
process b is run  
process a run

Thread instance

Because GIL exists in Cpython, multithreading will also become a thread on a single core cpu in practical application and run in queue.

import threading  
import time  
  
class ThreadTest (threading.Thread):  
    def __init__(self, name):  
        super().__init__()  
        self.name = name  
  
    def run(self):  
        while True:  
            print(f"i am in thread {self.name}")  
            time.sleep(1)  
  
  
if __name__ == "__main__":  
    threads = []  
    for i in range(4):  
        t = ThreadTest(i)  
        threads.append(t)  
      
    for t in threads:  
        t.start()  
      
    for t in threads:  
        t.join()

The thread class is implemented by inheriting threading.Thread, and then the object is generated by instantiation, and the thread can be started by calling the start() of the object.

Operation result

python3 thread_a.py  
i am in thread 0  
i am in thread 1  
i am in thread 2  
i am in thread 3  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1

Association

Python 3 adds asyncio to the standard library.

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

Operation result

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

summary

The above is all the content of this section. It mainly introduces the concepts and examples of processes, threads and coroutines. This article refers to the original- http://bjbsair.com/2020-03-22/tech-info/4425/ In the operating system, every program that runs independently occupies the resources allocated by the operating system. These programs do not interfere with each other and only run their own program code, which is the process.

However, when the operating system frequently creates the destruction process, a large number of system resources are wasted in the process of creation and destruction. With the emergence of multi-core cpu, threads have gradually replaced the process and become the basic unit of the operating system that can run independently.

When a process is not a multithreaded program, the only thread in the process is the code block that the process itself runs.

When multiple threads appear in a process, multiple threads share the resources of the process and accept the scheduling of the operating system to run each thread.

state

Association

To understand the concept of orchestration, let's first look at concurrency and parallelism.

parallel

Parallel is easy to understand, that is, there are multiple programs executing at the same time. The program here refers to the thread of the operating system.

Each cpu core can only run a set of instructions at the same time, which means that at the same time, there is only one thread executing on a core.

When the cpu has four cores, it can only execute four threads.

Concurrent

To understand concurrency, you need to know and.

Synchronous block

When an I/O operation in a program takes a long time, the program is not suspended, and has been waiting for network data transmission, unable to perform other operations, this is synchronous blocking.

One concept of synchronization is that after the network transmission is completed, the main program cannot be informed that the operation is completed, which leads to the main program:

  • Or you can only wait for I/O to complete
  • Or poll to see if the transmission is complete

Of course, other operations can be performed during polling. At this time, it is in the non blocking state, that is, synchronous non blocking.

Synchronous non blocking

The concept of non blocking means that the main program can perform other operations.

Asynchronous blocking

If there is synchronization, there is asynchrony.

Asynchronous blocking and synchronous blocking are the same. The main program does nothing and waits for the I/O operation to complete.

Asynchronous non blocking

Asynchronous non blocking state is the key to concurrency.

When the main program uses asynchronous I/O operation, it will not affect the subsequent operation of the main program. When the asynchronous I/O operation is completed, it will actively notify the main program to perform other operations, so as to reduce the resource consumption in the polling process and focus on other work.

Concurrent

Concurrency is a form of asynchronous non blocking state. When a program executes operation a, it makes the I/O of a asynchronous operation. At this time, the program executes operation b. externally, a and b are executed at the same time, but they only run in one thread.

Different from threads and processes, a cooperation program is not a program in the physical level of the operating system.

The process is program level, and the programmer controls the whole process life cycle. In this way, it can achieve the same effect as operating system multithreading, but it can save the resource consumption caused by off the shelf switching.

By using programs to manipulate the process, the cpu is running all the time, and it is the illusion that multiple processes are running all the time, which also becomes concurrency.

Example

Let's illustrate the relationship among processes, threads and coroutines in python with several examples.

Process instance

How do we write multiprocess programs in python?

The answer is to use the module multiprocessing for implementation.

import time  
from multiprocessing import Process  
  
class Test(Process):  
    def __init__(self):  
        super().__init__()  
      
    def run(self):  
        while True:  
            print("process b is run")  
            time.sleep(1)

By inheriting the multiprocessing Process, implementing the Process class, and then implementing the run method, you can realize the content of the Process to run in this method.

from process_b import Test  
import time  
  
if __name__ == "__main__":  
    t = Test()  
    t.start()  
    while True:  
        print("process a run")  
        time.sleep(1)

The calling method is also very simple, directly using Test to instantiate the object, then calling the member function start() of the object.

python3 process_a.py  
process a run  
process b is run  
process b is run  
process a run  
process a run  
process b is run  
process b is run  
process a run

Thread instance

Because GIL exists in Cpython, multithreading will also become a thread on a single core cpu in practical application and run in queue.

import threading  
import time  
  
class ThreadTest (threading.Thread):  
    def __init__(self, name):  
        super().__init__()  
        self.name = name  
  
    def run(self):  
        while True:  
            print(f"i am in thread {self.name}")  
            time.sleep(1)  
  
  
if __name__ == "__main__":  
    threads = []  
    for i in range(4):  
        t = ThreadTest(i)  
        threads.append(t)  
      
    for t in threads:  
        t.start()  
      
    for t in threads:  
        t.join()

The thread class is implemented by inheriting threading.Thread, and then the object is generated by instantiation, and the thread can be started by calling the start() of the object.

Operation result

python3 thread_a.py  
i am in thread 0  
i am in thread 1  
i am in thread 2  
i am in thread 3  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1  
i am in thread 3  
i am in thread 0  
i am in thread 2  
i am in thread 1

Association

Python 3 adds asyncio to the standard library.

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

Operation result

import asyncio  
import time  
  
  
async def test(num):  
    await asyncio.sleep(num)  
    print(num)  
  
  
async def run():  
    tasks = [asyncio.create_task(test(num)) for num in range(4)]  
    [await t for t in tasks]  
  
  
def run_main():  
    asyncio.run(run())  
  
  
if __name__ == "__main__":  
    run_main()

summary

The above is all the content of this section. It mainly introduces the concepts and examples of processes, threads and coroutines.

Tags: Programming Python network

Posted on Tue, 24 Mar 2020 03:59:34 -0400 by pohopo