从虚拟线程中的调用在主线程中执行Python函数 [英] Execute Python function in Main thread from call in Dummy thread

查看:456
本文介绍了从虚拟线程中的调用在主线程中执行Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Python script that handles aynchronous callbacks from .NET Remoting. These callbacks execute in a dummy (worker) thread. From inside my callback handler, I need to call a function I've defined in my script, but I need the function to execute in the main thread.

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

The Main thread is a remote client that sends commands to a server. Some of these commands result in asynchronous callbacks.

基本上,我需要等效于.NET的Invoke方法.这可能吗?

Basically, I need the equivalent of .NET's Invoke method. Is this possible?

推荐答案

您要使用队列类以建立一个队列,您的虚拟线程将使用函数填充该队列,而主线程将使用该队列.

You want to use the Queue class to set up a queue that your dummy threads populate with functions and that your main thread consumes.

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

然后永远阻止

这篇关于从虚拟线程中的调用在主线程中执行Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆