python - 在 python 中使用线程运行无限循环

标签 python multithreading opencv matplotlib

我的程序是这样设计的:

  1. 程序的第一部分从传感器获取实时值并使用 Matplotlib 绘制它。这必须长时间完成。此外,它将信息记录到数据库中。
  2. 第二部分是网络摄像机。我必须从 IP 摄像机获取输入并显示它。为了显示,我正在使用 OpenCV 的 imshow 方法。此外,我正在存储网络摄像机的视频。

问题:我已经准备好算法,问题是我需要在 while 循环中同时运行这两个算法。条件是我不能退出其中任何一个。现在线程是一个很好的替代方法,但我已经阅读了有关 GIL 的内容,那么我该如何运行两个无限循环呢?

from multiprocessing import Process

def methodA():
    while TRUE:
        do something

def methodB():
    while TRUE:
        do something

p=Process(target=methodA())
p.start()
p1=Process(target=methodB())
p1.start()

现在当我启动进程 p 时它开始执行,之后我如何启动 p1 来同时运行?

最佳答案

据我了解您的问题,您有两项不同的任务需要他们持续执行。现在关于你的问题:

how do I go about running two infinite loops?

您可以创建两个不同的线程来为您运行这些无限循环。第一个线程将执行您的任务 1,第二个线程将执行任务 2。

Also, once I start executing a thread, how do I execute the other thread when the first thread is running continuously/infinitely?

如果您使用两个不同的线程,则无需担心此问题。如果线程不共享任何资源,那么您无需担心这一事实。 如果您想从另一个线程停止/暂停一个线程,反之亦然,那么您可以使用标志或锁来实现一种机制。在这种情况下,这些问题会有所帮助:

Is there any way to kill a Thread in Python?

Why does the python threading.Thread object has 'start', but not 'stop'?

making-a-program-munltithreaded

使用线程的示例:

from threading import Thread

class myClassA(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'A'

class myClassB(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'B'


myClassA()
myClassB()
while True:
    pass

For shared resources?

使用Locks为他们。这里有些例子。 One , twoHow to synchronize threads in python?

what if I don't want to run it using classes? How do I do this using only methods?

from threading import Thread

def runA():
    while True:
        print 'A\n'

def runB():
    while True:
        print 'B\n'

if __name__ == "__main__":
    t1 = Thread(target = runA)
    t2 = Thread(target = runB)
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    while True:
        pass

关于python - 在 python 中使用线程运行无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23100704/

相关文章:

python - CVXPY:有效编写成对和的约束

python - 从嵌套列表中删除特定的列和行

python - 如何使用 Django 和 rest_framework 通过 url 中的外键检索对象

java - 如何使用多线程测试任务性能?

python - 使用 Python 的 Opencv : pointPolygonTest gives obviously wrong result

Python 3 套接字编程 : using sendall vs. sendto

python - 可以在 wsgi 应用程序中生成线程吗?

c++ - 如何正确使用互斥量作为线程中成员函数的参数?

python - 将遥测数据添加到视频 [python]

opencv - 关键点描述符向量的内容是什么?