MST

星途 面试题库

面试题:Python简单if语句在多线程并发控制场景的应用

在一个多线程的Python程序中,有多个线程同时操作一个共享资源(例如一个全局变量count)。要求使用简单if语句实现当count的值达到100时,暂停所有线程的操作,直到外部信号通知继续。请设计并实现相应的代码结构和逻辑,要考虑线程安全问题。
35.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import threading

count = 0
lock = threading.Lock()
pause_event = threading.Event()


def worker():
    global count
    while True:
        with lock:
            if count < 100:
                count += 1
                print(f"Thread {threading.current_thread().name} incremented count to {count}")
                if count == 100:
                    pause_event.clear()
                    print("Count has reached 100. Pausing all threads.")
            else:
                pause_event.wait()


threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()


# 模拟外部信号,当接收到外部信号时,调用以下代码继续线程操作
# pause_event.set()