006Python-threading__1

In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once(even though certain performance-oriented libraries might overcome this limitation).

But now,threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

Python通过threading模块来实现多线程,内部核心类是threading.Thread

参考链接:

官方文档

Runoob参考

The Thread class represents an activity that is run in a separate thread of control.

There are two ways to specify the activity:

  • by passing a callable object to the constructor;

  • by overriding the run() method in a subclass.

    No other methods (except for the constructor) should be overridden in a subclass.

    In other words, only override the __init__() and run() methods of this class.

Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception.

The is_alive() method tests whether the thread is alive.

Other threads can call a thread’s join() method. This blocks the calling thread until the thread whose join() method is called is terminated.

多线程基础

创建线程的两种方式

  1. 根据Thread构造函数直接实例化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import threading
    import time

    def print_numbers():
    for i in range(5):
    print(i)
    time.sleep(1)



    def test001():
    print("---1")
    thread = threading.Thread(target=print_numbers)
    print("---2")
    thread.start()
    print("---3")
    thread.join() ## 等待线程终止。默认情况下,join()会一直阻塞,直到被调用线程终止。如果指定了timeout参数,则最多等待timeout秒。
    print("---4")

    其输出如下:

    —1
    —2
    0
    —3
    1
    2
    3
    4
    —4

    从上可知,start方法之后,thread就会去处理其内部的任务;join会阻塞当前线程,知道我们创建的thread调用终止,才会继续执行当前线程(主线程);

    threading模块里有很多好用的方法,比如查看当前线程threading.current_thread(),具体可以查看官方文档。

  2. 继承Thread并重写__init__(如果需要额外参数) 和 run() 方法.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    exit_flag = False

    class MyThread(threading.Thread):
    def __init__(self, thread_id, name, delay):
    super().__init__()
    self.thread_id = thread_id
    self.name = name
    self.delay = delay

    def run(self):
    print(f"Starting {self.name}")
    print_time(self.name, self.delay, 5)
    print(f"Exiting {self.name}")


    def print_time(thread_name, delay, counter):
    while counter:
    if exit_flag:
    thread_name.exit()
    time.sleep(delay)
    print(f"{thread_name} : {time.ctime(time.time())}")
    counter -= 1


    def test002():
    thread1 = MyThread(1, "Thread-1", 1)
    thread2 = MyThread(2, "Thread-2", 2)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

    运行上述代码输出如下:

    Starting Thread-1
    Starting Thread-2
    Thread-1 : Wed Mar 19 13:11:45 2025
    Thread-2 : Wed Mar 19 13:11:46 2025
    Thread-1 : Wed Mar 19 13:11:46 2025
    Thread-1 : Wed Mar 19 13:11:47 2025
    Thread-2 : Wed Mar 19 13:11:48 2025
    Thread-1 : Wed Mar 19 13:11:48 2025
    Thread-1 : Wed Mar 19 13:11:49 2025
    Exiting Thread-1
    Thread-2 : Wed Mar 19 13:11:50 2025
    Thread-2 : Wed Mar 19 13:11:52 2025
    Thread-2 : Wed Mar 19 13:11:54 2025
    Exiting Thread-2


006Python-threading__1
https://jackiedai.github.io/2025/03/18/011Python/008Python-threading1/
Author
lingXiao
Posted on
March 18, 2025
Licensed under