Skip to main content
 首页 » 编程设计

python之monkey_patch(time=True) 如何影响 eventlet.spawn

2025年05月04日13mengfanrong

一般情况下,在使用greenthread时,我可以这样写代码:

def myfun(): 
    print "in my func" 
eventlet.spawn(myfunc) 
eventlet.sleep(0)  #then myfunc() is triggered as a thread. 

但是在使用money_patch(time=true)之后,我可以将代码更改为:

eventlet.monkey_patch(time=True) 
eventlet.spawn(myfunc) # now myfunc is called immediately 

为什么这次我不需要调用eventlet.sleep(0)?

在我编写自己的 sleep 函数之后:

def my_sleep(seconds): 
    print "oh, my god, my own..." 

并将内置时间模块的sleep attr设置为my_sleep func,然后我发现my_sleep func会被调用很多次并输出很多。 但是我在 eclipse 中只能看到一个调试线程,它没有调用 my_sleep func。

所以,结论是,sleep函数默认是不断调用的,我想eventlet的作者是知道这一点的,所以他们开发了monkey_patch()函数。是这样吗?

#

根据@temoto 的回答,CPython 无法重现相同的结果。我想我应该添加一些消息来介绍我是如何发现这个有趣的东西的。(为什么我第一次没有添加这条消息,因为输入这么多单词并不容易,而且我的英语也不是很好。^^)

我在使用 eclipse 远程调试 openstack 代码时发现了这个东西。

在nova/network/model.py中,一个函数是这样写的:

class NetworkInfoAsyncWrapper(NetworkInfo): 
    """Wrapper around NetworkInfo that allows retrieving NetworkInfo 
    in an async manner. 
 
    This allows one to start querying for network information before 
    you know you will need it.  If you have a long-running 
    operation, this allows the network model retrieval to occur in the 
    background.  When you need the data, it will ensure the async 
    operation has completed. 
 
    As an example: 
 
    def allocate_net_info(arg1, arg2) 
        return call_neutron_to_allocate(arg1, arg2) 
 
    network_info = NetworkInfoAsyncWrapper(allocate_net_info, arg1, arg2) 
    [do a long running operation -- real network_info will be retrieved 
    in the background] 
    [do something with network_info] 
    """ 
 
    def __init__(self, async_method, *args, **kwargs): 
        self._gt = eventlet.spawn(async_method, *args, **kwargs) 
        methods = ['json', 'fixed_ips', 'floating_ips'] 
        for method in methods: 
            fn = getattr(self, method) 
            wrapper = functools.partial(self._sync_wrapper, fn) 
            functools.update_wrapper(wrapper, fn) 
            setattr(self, method, wrapper) 

当我第一次调试这个函数时,执行后

self._gt = eventlet.spawn(async_method, *args, **kwargs)

立即执行回调函数async_method。但请记住,这是一个线程,它应该由eventlet.sleep(0)触发。

但我没有找到调用sleep(0)的代码,所以如果sleep可能被eclipse调用,那么在现实世界(非调试世界) ,是谁触发的?

请您参考如下方法:

TL;DR:Eventlet API 不需要sleep(0) 来启动绿色线程。 spawn(fun) 将在未来某个时间开始运行,包括现在。您只应调用 sleep(0) 以确保它现在开始,即便如此,最好使用显式同步,例如 Event 或信号量。

我无法在 IPython 或纯 Python 控制台中使用 CPython 2.7.6 和 3.4.3、eventlet 0.17.4 重现此行为。所以可能是 Eclipse 在后台调用 time.sleep。

monkey_patch 是作为运行所有(和第三方)代码并替换 time.sleep -> eventlet.sleep 的快捷方式引入的,对于 os, socket 等模块。它与 Eclipse(或其他东西)重复 time.sleep 调用无关。

但这是一个有趣的观察,谢谢。