MST
星途 面试题库

面试题:Python中线程安全机制之内置数据结构的线程安全性

在Python中,像列表(list)、字典(dict)这样的内置数据结构是否是线程安全的?如果不是,如何使其在线程环境中安全使用?
41.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

在Python中,像列表(list)、字典(dict)这样的内置数据结构不是线程安全的

要使其在线程环境中安全使用,可以采用以下几种方法:

  • 使用锁(threading.Lock
import threading

my_list = []
lock = threading.Lock()

def add_to_list(item):
    with lock:
        my_list.append(item)


  • 使用队列(queue.QueueQueue 是线程安全的,常用于在多线程之间安全地传递数据。
from queue import Queue

my_queue = Queue()

def producer():
    for i in range(5):
        my_queue.put(i)


def consumer():
    while True:
        item = my_queue.get()
        if item is None:
            break
        print(f"Consumed: {item}")
        my_queue.task_done()


  • 使用线程安全的集合(collections.dequecollections.deque 是线程安全的双端队列,某些场景下可以替代列表实现线程安全的数据结构。
from collections import deque
import threading

my_deque = deque()
lock = threading.Lock()

def append_to_deque(item):
    with lock:
        my_deque.append(item)


  • 使用 threading.local():这允许每个线程拥有自己的数据副本,避免了共享数据带来的竞争问题。
import threading

local_data = threading.local()

def set_local_value(value):
    local_data.value = value


def get_local_value():
    return local_data.value