繁体   English   中英

从虚拟线程中的调用在主线程中执行 Python 函数

[英]Execute Python function in Main thread from call in Dummy thread

我有一个 Python 脚本来处理来自 .NET Remoting 的异步回调。 这些回调在一个虚拟(工作)线程中执行。 在我的回调处理程序中,我需要调用我在脚本中定义的函数,但我需要在主线程中执行该函数。

主线程是一个向服务器发送命令的远程客户端。 其中一些命令会导致异步回调。

基本上,我需要相当于 .NET 的 Invoke 方法。 这可能吗?

您想使用Queue (现在是 python 3 中的队列)类来设置一个队列,您的虚拟线程用函数填充该队列并且您的主线程使用该队列

import Queue

#somewhere accessible to both:
callback_queue = Queue.Queue()

def from_dummy_thread(func_to_call_from_main_thread):
    callback_queue.put(func_to_call_from_main_thread)

def from_main_thread_blocking():
    callback = callback_queue.get() #blocks until an item is available
    callback()

def from_main_thread_nonblocking():
    while True:
        try:
            callback = callback_queue.get(False) #doesn't block
        except Queue.Empty: #raised when queue is empty
            break
        callback()

演示:

import threading
import time

def print_num(dummyid, n):
    print "From %s: %d" % (dummyid, n)
def dummy_run(dummyid):
    for i in xrange(5):
        from_dummy_thread(lambda: print_num(dummyid, i))
        time.sleep(0.5)
    
threading.Thread(target=dummy_run, args=("a",)).start()
threading.Thread(target=dummy_run, args=("b",)).start()

while True:
    from_main_thread_blocking()

印刷:

From a: 0
From b: 0
From a: 1
From b: 1
From b: 2
From a: 2
From b: 3
From a: 3
From b: 4
From a: 4

然后永远阻塞

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM