5

How can I achieve communication between threads?

I have one thread in which I do some stuff, then I need to call a method from an object that lives in the main program thread and this method should be executed in the main process:

class Foo():
    def help(self):
        pass


class MyThread(threading.Thread):

    def __init__(self, connection, parser, queue=DEFAULT_QUEUE_NAME):
        threading.Thread.__init__(self)

    def run(self):
        # do some work
        # here I need to call method help() from Foo()
        # but I need to call it in main process


bar = Foo()

my_work_thread = MyThread()
my_work_thread.run()
2
  • Both threads have access to the same memory, so bar in the separate thread is identical to bar in the main thread Commented Jul 11, 2018 at 11:51
  • 1
    Hard to tell, what you wanna do. What does help() do? Why you need to call it from the main process? Does help() depend ons some variables available only in the main process? Normally you can share variables between threads, just remember to make them thread-safe (locking) Commented Jul 11, 2018 at 11:52

1 Answer 1

6

There are many possibilities how to do it, one is using 2 queues:

from time import sleep
import threading, queue

class Foo():
    def help(self):
        print('Running help')
        return 42


class MyThread(threading.Thread):

    def __init__(self, q_main, q_worker):
        self.queue_main = q_main
        self.queue_worker = q_worker
        threading.Thread.__init__(self)

    def run(self):
        while True:
            sleep(1)
            self.queue_main.put('run help')
            item = self.queue_worker.get()      # waits for item from main thread
            print('Received ', item)

queue_to_main, queue_to_worker = queue.Queue(), queue.Queue( )
bar = Foo()

my_work_thread = MyThread(queue_to_main, queue_to_worker)
my_work_thread.start()

while True:
    i = queue_to_main.get()
    if i == "run help":
        rv = Foo().help()
        queue_to_worker.put(rv)

Output:

Running help
Received  42
Running help
Received  42
Running help
Received  42
...etc
Sign up to request clarification or add additional context in comments.

2 Comments

Great thanks! But, the only thing that embarrasses me: a while loop in the main process. Do we can to use something like subscribers? E.g.: when something appends to queue, then run function on_queue_append()?
@Q-bart There aren't any subscribers in Python queue, but you can use get_nowait() just to peek if something is in the queue: docs.python.org/3/library/queue.html#queue.Queue.get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.