How to receive thread callbacks in Python

2 Answers

0 votes
import threading
import queue
import time

# The worker thread pushes results into a queue, and the main thread reads them.

def worker(q):
    for i in range(5):
        time.sleep(1)
        q.put(f"Callback from thread: {i}")

def main():
    q = queue.Queue()
    t = threading.Thread(target=worker, args=(q,))
    t.start()

    while True:
        msg = q.get()
        print("Main received:", msg)

main()

 
 
 
'''
run:
 
Main received: Callback from thread: 0
Main received: Callback from thread: 1
Main received: Callback from thread: 2
Main received: Callback from thread: 3
Main received: Callback from thread: 4
 
'''

 



answered Jan 1 by avibootz
0 votes
import threading
import time

# You can pass a function into the thread and call it from inside.

def callback(result):
    print("Callback received:", result)

def worker(cb):
    for i in range(5):
        time.sleep(1)
        cb(i)

t = threading.Thread(target=worker, args=(callback,))
t.start()

 
 
 
'''
run:
 
Callback received: 0
Callback received: 1
Callback received: 2
Callback received: 3
Callback received: 4
 
'''

 



answered Jan 1 by avibootz
...