【问题标题】:Start a thread inside a function在函数内启动线程
【发布时间】:2023-04-06 12:00:01
【问题描述】:

我正在尝试执行具有如下结构的代码:

import things
...
class MyThreadRead(Thread):
    ...
    def run(self):
        global cap
        global frame_resized
        global netMain
        ...
        ret, frame = cap.read()
        frame_resized = cv2.resize(...)

...
...
def YOLO():
    ...
    global frame_resized
    global cap
    ...
    cap = cv2.VideoCapture(...)
    ...
    while True:
        ...
        readFrameThread.start()
        detections = detect(a, b, frame_resized, c)
        ...
    readFrameThread.join()
...
...
if __name__== "__main__":
    readFrameThread = MyThreadRead(1)
    YOLO()

当我执行此脚本时,我在 YOLO 函数内的函数检测行中收到此错误:

NameError: global name ´frame_resized´ is not defined

我应该在哪里声明全局变量?在 YOLO 函数内部还是外部?

【问题讨论】:

  • 你根本不应该使用全局变量。
  • 您可以将它包装在一个单格子类中,并具有属性的线程保存访问权限

标签: python python-2.7 global-variables python-multithreading


【解决方案1】:

你应该像这样在全局级别定义它

if __name__== "__main__":
    frame_resized = None
    readFrameThread = MyThreadRead(1)
    YOLO()

但最好完全避免使用全局变量。有很多方法可以做到这一点,一种是创建数据容器并将其传递给各方。它看起来像这样:

class Container:
    def __init__(self):
        self.cap = None
        self.frame_resized = None
        self.netMain  = None

class MyThreadRead(Thread):
    def __init__(self, container):
        self.container = container

    def run(self):
        ret, frame = self.container.cap.read()
        self.container.frame_resized = cv2.resize(...)

def YOLO(container, trd):
    container.cap = cv2.VideoCapture(...)
    ...
    while True:
        ...
        readFrameThread.start()
        detections = detect(a, b, container.frame_resized, c)
        ...
    trd.join()

if __name__== "__main__":
    container = Container()
    readFrameThread = MyThreadRead(1, container)
    YOLO(container, readFrameThread)

在选择如何实现容器时,不要忘记,namedtuples 是只读的,不适合您的情况。

【讨论】:

  • 我应该对 cap 对象做同样的事情吗?
  • 如果你真的想使用全局变量,答案是肯定的,你应该全部定义。
  • 如果我需要与另一个线程共享 frame_resized 对象,如何避免使用全局变量?因为我打算用另一个线程来执行检测功能。
  • 将它们作为参数传递
  • 好的,我会试试你的建议。感谢大家的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2014-02-03
  • 1970-01-01
  • 2021-09-25
相关资源
最近更新 更多