import threading
def square_number(numbers, start, end, result):
for i in range(start, end):
result[i] = numbers[i] ** 2
def square_list_with_threads(numbers):
num_threads = 4
chunk_size = len(numbers) // num_threads
threads = []
result = [0] * len(numbers)
for i in range(num_threads):
start = i * chunk_size
end = (i + 1) * chunk_size if i < num_threads - 1 else len(numbers)
thread = threading.Thread(target=square_number, args=(numbers, start, end, result))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
return result
GIL的影响
- 原理:在CPython解释器中,GIL会确保同一时刻只有一个线程能够执行Python字节码。这意味着,即使在多核CPU环境下,多个Python线程也无法真正地并行执行Python代码。
- 对本场景的影响:
- 计算密集型任务:对数字进行平方运算属于计算密集型任务。由于GIL的存在,多线程并不能充分利用多核CPU的优势来提高运算速度。每个线程在执行平方运算时,需要获取GIL,在单核上依次执行,所以实际上并没有并行加速。
- 多线程开销:虽然不能并行加速,但多线程本身带来了额外的开销,例如线程的创建、调度和切换等。这可能导致使用多线程实现的平方运算比单线程实现还要慢。在这种计算密集型场景下,使用多进程(
multiprocessing
模块)可能是更好的选择,因为多进程可以绕过GIL限制,充分利用多核CPU资源实现并行计算。