面试题答案
一键面试在Python中,像列表(list)、字典(dict)这样的内置数据结构不是线程安全的。
要使其在线程环境中安全使用,可以采用以下几种方法:
- 使用锁(
threading.Lock
):
import threading
my_list = []
lock = threading.Lock()
def add_to_list(item):
with lock:
my_list.append(item)
- 使用队列(
queue.Queue
):Queue
是线程安全的,常用于在多线程之间安全地传递数据。
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.deque
):collections.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