python - 有没有办法在 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()
这没用
解决方案
您可以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
)的情况下,这两者都将永远运行。
推荐阅读
- ruby - 哪些类是 Rails 可缓存的
- php - 案例发生变化时如何区分州、城市和邮政编码
- reactjs - 材质 UI 布局 - 3 列
- pandas - 如何在数据框中拆分这种列?
- android - 如果与firestore中的数组存在相同的数据,如何检查并显示错误
- mongodb - MongoDB 聚合查询,登录平均数
- javascript - 为什么 p 的值是假的?
- python - 使用 pandas to_sql 获取导致错误的记录行/列
- go - 如何在 Hugo 中解析变量返回的路径字符串中的括号?
- php - 如何在 PHP 中调用 AWS API 的 GetCostAndUsage