【问题标题】:QThreads Python - CommunicatingQThreads Python - 通信
【发布时间】:2015-08-31 22:29:35
【问题描述】:

我只是想知道是否可以在两个 QThread 之间进行数据通信。我已经知道如何在 QThread 启动之前输入数据,然后调用 run 方法。 但是我有一种情况,我使用 QThread (A) 从伺服电机控制器获取串行数据并使用主 GUI 显示它。我还运行另一个 Qthread (B),它执行几个长进程(在 Qthard (B) 内执行大约 1000 行代码)。 QThread(B)执行到一半,我想使用QThread(A)中的串行数据并将其记录在QThread(B)中。当 QThread (B) 准备好记录时,必须尝试将串行数据从 QThread (A) 通过管道传输到 QThread (B)。

这样做的最佳方法是什么?我试过使用全局变量,但没有成功。还有哪些其他选择?

谁能给我一些建议,在此先感谢!

桑卡:)

【问题讨论】:

  • 你应该使用队列,python中关于并发的演示link

标签: python user-interface qthread


【解决方案1】:

您可以为此使用 Queue(只是一个示例):

from queue import Queue
from threading import Thread

# A thread that produces data
def producer(out_q):
    while True:
        # Produce some data
        ...
        out_q.put(data)


# A thread that consumes data
def consumer(in_q):
    while True:
        # Get some data
        data = in_q.get()
        # Process the data
        ...

# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()

更新:QThreads https://stackoverflow.com/a/25109185/1698180 的更具体示例

【讨论】:

  • 感谢您的重播。这是否意味着两个线程需要同时启动,或者我可以让 t1 产生一段时间的数据,然后启动 t2 并在 t1 和 t2 之间进行通信
  • 您不必同时启动线程,只要生产者将“消息”存储到队列中,您就可以在之后消费它们。多线程/多处理应用程序的问题 - 每个线程/进程都有自己的堆栈,并且无法直接在对象之间进行通信,因此您需要使用队列。
  • Ievgen Aleinikov 感谢您的建议,我设法让队列正常工作,而且效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
相关资源
最近更新 更多