【问题标题】:How do I update and retrieve an image using multiprocessing python?如何使用多处理 python 更新和检索图像?
【发布时间】:2018-12-28 17:22:44
【问题描述】:

在我的代码中,我有两个函数,第一个函数operate_camera 更新存储变量。第二个函数print_func 打印存储变量。

我想同时运行这两个函数,打印过程延迟 15 秒。然而operate_camera 函数包含一个while 循环。并且通过运行脚本,它只会运行一次进程p2,并且会停留在进程p1

为简单起见,我在以下代码中使用简单的一维数组。

from multiprocessing import Process, Array 
import numpy as np 
import time

def operate_camera(store):
    while True: # loop that updates image
        store = store + np.ones_like(store)

def print_func(store):
    print(store)
    time.sleep(15)

if __name__ == "__main__":
    store = np.array([0,0,0])

    p1 = Process(target=operate_camera, args=(store,))
    p2 = Process(target=print_func, args=(store,))

    p1.start()    
    p2.start()

输出只会卡在

[0,0,0]

多处理包中是否有任何解决方案可以让我保留这种形式的代码。如果没有,是否有任何替代解决方案来解决这个问题?

【问题讨论】:

  • 您是否尝试过拿出时钟并等待整整一分钟?另外,感谢minimal reproducible example
  • 由于您使用的是多处理,您可以在 print_func 中使用另一个 while 循环来不断打印您的值并同时使用 operate_camera 更新它们

标签: python python-multiprocessing python-multithreading


【解决方案1】:

首先,你真的想要多处理而不是多线程吗? 你要求替代解决方案,所以,我想出了多线程来解决这个问题。为了清楚起见,您应该检查this answer,其中讨论了大多数相同的问题。所以,我认为问题在于你的 print 函数只执行一个,因此你还需要一个循环。

from threading import Thread
import numpy as np
import time

store = np.array([0, 0, 0])


def operate_camera():
    while True:
        global store
        store += np.ones_like(store)


def print_func():
    while True:
        time.sleep(15)
        print(store)


if __name__ == "__main__":

    t1 = Thread(target=operate_camera)
    t2 = Thread(target=print_func)

    t1.start()
    t2.start()

    # other code

    t1.join()
    t2.join()

您可以注意到,此代码使用全局对象,这不是最佳实践,但我们需要一个共享对象。

如果是带参数的函数

from threading import Thread
import numpy as np
import time


def operate_camera(store):
    while True:
        store += np.ones_like(store)


def print_func(store):
    time.sleep(1)
    print(store)


if __name__ == "__main__":
    store = np.array([0, 0, 0])

    camera_thread = Thread(target=operate_camera, args=(store, ))
    camera_thread.setDaemon(True)
    camera_thread.start()

    while True:
        print_func(store)

【讨论】:

  • 您好,感谢您的帮助。如果我有另一个打印功能,例如print_func1(),这会起作用吗?
  • @Tian 是的,在上面的示例中创建一个新线程作为camera_thread,并将其与第一个示例结合起来。另外,如果这有帮助,您可以标记答案
  • 好的,我也想检查一下。两个函数在不同时间访问同一个 store 变量,再加上operate_camera function 不断更新 store 变量,会不会出现任何错误?还有,camera_thread.setDaemon(True)有什么用?
猜你喜欢
  • 2015-06-17
  • 2016-10-21
  • 1970-01-01
  • 2015-05-03
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2022-06-15
相关资源
最近更新 更多