首页 > 解决方案 > 有没有办法在 Python 中同时执行多个 while 循环?

问题描述

我有几个从共享内存读取和写入数据的函数,它们由 while 循环执行。

例如,

def functionA():
    while True:
         # read data from shared memory
         # manipulate data and write again to shared memory

def functionB():
    while True:
         # read data from shared memory at the same time with functionA()
         # manipulate data (different way with functionA()) and write to shared memory(also different)

在这种情况下,如何在一个主函数中执行两个函数?

我尝试了多进程,如下所示

if __name__ == '__main__':
    A = Process(target=functionA)
    B = Process(target=functionB)
    A.start()
    B.start()
    A.join()
    B.join()

这没用

标签: pythonmultithreadingwhile-loop

解决方案


您可以threading以非常相似的方式使用:

from threading import Thread, Lock

而且你的台词几乎不需要改变:

if __name__ == '__main__':
    A = Thread(target=functionA)
    B = Thread(target=functionB)
    A.start()
    B.start()
    A.join()
    B.join()

但是,您应该注意,在两个线程中同时操作同一个对象而不使用一些更安全的方法(如Lock(上面导入的))不是“线程安全的”。所以你的功能可能需要改变一点:

non_thread_safe_object = list() # Just an example
lock = Lock()

def functionA():
    while True:
        with lock:
            non_thread_safe_object.append('something')
        unrelated_code()

def functionB():
    while True:
        with lock:
            non_thread_safe_object.append('something else')
        other_unrelated_code()

这两个可以同时运行,因为lock确保在任何给定时间只运行一个不安全的操作,而其他不相关的操作可以在遇到该代码时发生。

另请注意,在不破坏循环(和使用while True)的情况下,这两者都将永远运行。


推荐阅读