MST
星途 面试题库

面试题:Python多线程在数据处理中的基础应用

假设你有一个包含大量数字的列表,需要对每个数字进行平方运算并返回结果列表。请用Python多线程实现该功能,并说明GIL(全局解释器锁)对这个过程可能产生的影响。
32.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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的影响

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