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
参考链接:
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__()
andrun()
methods of this class.Once a thread object is created, its activity must be started by calling the thread’s
start()
method. This invokes therun()
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 whosejoin()
method is called is terminated.
多线程基础
创建线程的两种方式
-
根据
Thread
构造函数直接实例化1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import 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()
,具体可以查看官方文档。 -
继承
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
31exit_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