我的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. TheQueue
class in this module implements all the required locking semantics.
关于python - python中主线程和子线程之间的原子操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11843141/