MST

星途 面试题库

面试题:Python多线程中如何使用锁来同步资源

在Python多线程编程场景下,假设你有一个共享变量`counter`,多个线程会对其进行加1操作。请使用`threading.Lock`来确保`counter`的操作是线程安全的,写出完整的Python代码示例。
47.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import threading

# 共享变量
counter = 0
# 创建锁对象
lock = threading.Lock()


def increment():
    global counter
    for _ in range(100000):
        # 获取锁
        lock.acquire()
        try:
            counter += 1
        finally:
            # 释放锁
            lock.release()


# 创建多个线程
threads = []
for _ in range(5):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

# 等待所有线程完成
for t in threads:
    t.join()

print(f"Final counter value: {counter}")