Python – Call a method in a thread, python, from another thread

Call a method in a thread, python, from another thread… here is a solution to the problem.

Call a method in a thread, python, from another thread

How do I implement inter-thread communication?

I have a thread

where I do something, and then I need to call a method from an object in the main program thread, 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()

Solution

There are many possibilities how to do this, one is to use 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

Related Problems and Solutions