我想从后台回调到主线程执行我的代码。由于某些原因,我没有找到执行此操作的简单示例。
我找到了队列和池的示例,这显然不是我想要的。我只想加入主线程来执行我的函数。
这是一些简单的代码:
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“测试”事件的回调。但由于事件不是在同一个线程中触发,这给我带来了一些麻烦:
# async call !
def event_cb(num):
sio.emit('test')
GPIO.add_event_detect(btNumber, GPIO.RISING, event_cb)
调用测试方法装饰器: 但是当发出不是在主线程上完成时,这将停止工作。
只要套接字调用是从主线程完成的,就可以了。 但是当在 DummyThread 上完成一次调用时,这就不再起作用了。
我在带有 socket.io 实现的客户端设备上进行测试。只要“发出”在主线程上完成,它就可以工作,但是当我在另一个线程上执行时(例如触发回调的按钮,它就会停止工作)
这就是我愿意表演的原因
最佳答案
您可以使用 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()
关于python - 如何从另一个线程上调用的回调返回主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35550501/