簡體   English   中英

如何從另一個線程上調用的回調返回主線程

[英]How to return to the main thread from a callback called on another thread

我想從后台回調執行代碼到主線程。 由於某些原因,我沒有找到執行該操作的簡單示例。

我發現了帶有隊列和池的示例,這顯然不是我想要的。 我只想加入主線程以執行我的功能。

這是一些簡單的代碼:

def my_callback:
    # this callback is called from a third party and I don't have control on it. 
    # But because of this, the function must_be_executed_on_main_thread is
    # executed on the background.
    must_be_executed_on_main_thread()

def must_be_executed_on_main_thread:
    # must be executed on the main thread.

**編輯**

這是我的問題:主文件:

if __main__ == '__main__'
    sio = socketio.Server()
    app = Flask(__name__)
    app = socketio.Middleware(sio, app)

    # now the thread is blocking into the server pool
    eventlet.wsgi.server(eventlet.listen('', 7000)), app)

從另一個文件中,我有一個裝飾器來處理套接字事件:

@sio.on('test')
def test(sid, data):
    print threading.currentThread()
    sio.emit('event triggered')

問題就在這里:我有一些由硬件按鈕觸發的事件,這些事件觸發了一個回調,該回調調用了sio“ test”事件。 但是由於事件未觸發到同一線程中,這給我帶來了一些麻煩:

# async call !
def event_cb(num):
    sio.emit('test')

GPIO.add_event_detect(btNumber, GPIO.RISING, event_cb)

測試方法裝飾器被調用:但是當不在主線程上完成發射時,此方法將停止工作。

只要從Mainthread完成套接字調用,就可以了。 但是當對DummyThread進行一次調用時,此操作不再起作用。

我在具有socket.io實現的客戶端設備上進行測試。 只要“ emit”在主線程上完成,它就可以工作,但是當我在另一個線程上執行時(例如使用觸發回調的按鈕,它就停止工作)

這就是為什么我喜歡表演

您可以使用Queue實例輕松地在線程之間傳遞值。

這個簡單的演示腳本解釋了這個概念。 您可以使用Ctrl - C中止腳本。

#!/usr/bin/env python
import Queue
import random
import threading
import time

def main_thread():
    """Our main loop in the main thread.

    It receives the values via a Queue instance which it passes on to the
    other threads on thread start-up.
    """
    queue = Queue.Queue()

    thread = threading.Thread(target=run_in_other_thread,
                              args=(queue,))
    thread.daemon = True  # so you can quit the demo program easily :)
    thread.start()

    while True:
         val = queue.get()
         print "from main-thread", val

def run_in_other_thread(queue):
    """Our worker thread.

    It passes it's generated values on the the main-thread by just
    putting them into the `Queue` instance it got on start-up.
    """
    while True:
         queue.put(random.random())
         time.sleep(1)

if __name__ == '__main__':
    main_thread()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM