Reputation: 55
I was just wondering whether its possible to communicate data between Two QThreads. I already know how to enter data before a QThread Starts and then invoke the run method. But I have a situation where I use a QThread (A) to acquire serial data from a Servo Motor controller and display it using a Main GUI. I also run another Qthread (B) which does several long processes (roughly about 1000 lines of code executing inside Qtheard (B)). Half way through the execution of QThread (B), I want to use the serial data in QThread (A) and log it inside QThread (B). Essential try to pipe the serial data from QThread (A) into QThread (B) when QThread (B) is ready to log.
What is the best way of doing this? I've tried using a global variable, but has had no success. What other options are available?
Please can someone give me some advice, thanks in advance!
Sanka :)
Upvotes: 1
Views: 115
Reputation: 91
You could use Queue for that (just an example):
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()
UPDATE: more specific example for QThreads https://stackoverflow.com/a/25109185/1698180
Upvotes: 1