Python中如何使用线程

Python中如何使用线程

技术背景

在Python编程中,线程是实现并发执行的一种方式。通过多线程,可以让程序在同一时间执行多个任务,从而提高程序的效率。不过,由于Python的全局解释器锁(GIL)的存在,Python的多线程在CPU密集型任务中并不能真正实现并行执行,只有在I/O密集型任务中才能发挥优势。

实现步骤

简单多线程示例

使用multiprocessing.dummy中的Pool来实现简单的多线程:

1
2
3
4
5
6
7
8
9
10
11
12
from multiprocessing.dummy import Pool as ThreadPool

def my_function(item):
# 这里是具体的处理逻辑
return item * 2

my_array = [1, 2, 3, 4]
pool = ThreadPool(4)
results = pool.map(my_function, my_array)
pool.close()
pool.join()
print(results)

使用threading模块

1
2
3
4
5
6
7
8
9
10
11
12
13
import threading

def print_number(number):
print(f"Thread {number} is running")

thread_list = []
for i in range(10):
t = threading.Thread(target=print_number, args=(i,))
thread_list.append(t)
t.start()

for thread in thread_list:
thread.join()

使用concurrent.futures模块

1
2
3
4
5
6
7
8
9
10
import concurrent.futures

def square(x):
return x * x

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {executor.submit(square, i): i for i in range(10)}
for future in concurrent.futures.as_completed(futures):
result = future.result()
print(result)

核心代码

处理URL请求的多线程示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import urllib.request
from multiprocessing.dummy import Pool as ThreadPool

urls = [
'http://www.python.org',
'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/',
'http://www.python.org/getit/',
'http://www.python.org/community/',
'https://wiki.python.org/moin/',
]

pool = ThreadPool(4)
results = pool.map(urllib.request.urlopen, urls)
pool.close()
pool.join()

for result in results:
print(len(result.read()))

传递多个参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import itertools
from multiprocessing.dummy import Pool as ThreadPool

def function(a, b):
return a + b

list_a = [1, 2, 3]
list_b = [4, 5, 6]
constant = 10

pool = ThreadPool(4)
results1 = pool.starmap(function, zip(list_a, list_b))
results2 = pool.starmap(function, zip(itertools.repeat(constant), list_a))
pool.close()
pool.join()

print(results1)
print(results2)

最佳实践

  • I/O密集型任务:使用threadingconcurrent.futures.ThreadPoolExecutor模块。例如,在处理网络请求、文件读写等任务时,多线程可以让程序在等待I/O操作完成的同时继续执行其他任务,从而提高效率。
  • CPU密集型任务:使用multiprocessingconcurrent.futures.ProcessPoolExecutor模块。由于GIL的存在,Python的多线程在CPU密集型任务中无法真正并行,而多进程可以利用多个CPU核心,实现真正的并行计算。
  • 线程安全:在多线程编程中,要注意线程安全问题。可以使用Queue来进行线程间的数据传递和同步,避免使用锁等复杂的同步机制。

常见问题

GIL问题

由于GIL的存在,Python的多线程在CPU密集型任务中并不能真正实现并行执行。解决方法是使用多进程来处理CPU密集型任务。

线程同步问题

在多线程编程中,如果多个线程同时访问和修改共享资源,可能会导致数据不一致等问题。解决方法是使用线程安全的数据结构(如Queue)或同步机制(如锁、信号量等)。

线程池管理

在使用线程池时,要注意合理设置线程池的大小。如果线程池过大,会导致系统资源浪费;如果线程池过小,可能无法充分发挥多线程的优势。


Python中如何使用线程
https://119291.xyz/posts/how-to-use-threading-in-python/
作者
ww
发布于
2025年6月4日
许可协议