python - python中主线程和子线程之间的原子操作

标签 python multithreading atomic

我的Python程序中有一个列表,它在某些情况下获取新项目(它是一个消息队列消费者)。然后我有一个线程,每隔几分钟检查列表中是否有任何内容,如果有,那么我想对每个项目执行一个操作,然后清空列表。

现在我的问题是:我应该使用锁来确保子线程中的操作是原子的,这是否可以确保主线程在我浏览列表时无法更改列表?
或者我应该使用某种标志?

伪代码让我的问题更清楚。

子线程:

def run(self):
    while 1:
        if get_main_thread_list() is not empty:
            do_operations()
        empty_the_list()
        sleep(30)

主线程:

list = []

def on_event(item):
    list.add(item)

def main():
    start_thread()
    start_listening_to_events()

我希望这能让我的问题更加清晰,并且显然欢迎任何资源或评论的链接!

PS:我很清楚,对于这个问题,我可能无法很好地掌握线程编程,如果您相信的话,如果您有时间,请花一些时间解释一下我的推理有什么问题。

最佳答案

should I use locks to ensure that the action in the subthread is atomic, and does this ensure that the main thread can't alter the list while I'm going through the list?

是的。如果你正确实现它,是的。

Or should I instead use some kind of flag?

“某种标志”==锁,所以你最好使用线程锁。

重要提示:在我看来,您正在尝试重新实现 queue来自 stdlib 的模块,您可能想看一下。

除了拥有一堆有趣的功能之外,它也是线程安全的:

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

关于python - python中主线程和子线程之间的原子操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11843141/

相关文章:

python - 如何使用套接字获取 Asterisk 服务器的状态 - Python

python - matplotlib 中 plt.draw() 和 plt.show() 的区别

python - PIL ImageGrab 返回 24 位图像而不是 32 位

multithreading - 在 Delphi 中的每个内核中运行线程

multithreading - Visual C++ (CLI) 线程

windows - 对于 64 位 Windows 上的 32 位应用程序,64 位操作是原子的吗

Windows 上 Visual Studio 2017 中的 Python 包(numpy/pandas/等)

c++ - 在 OpenMP 线程中充分私有(private)化数据

concurrency - Event Sourcing/CQRS对聚合、原子性、并发和最终一致性的疑惑

language-agnostic - 安全寄存器,常规寄存器和原子寄存器有什么区别?