2011-12-24 26 views
2

我有一个多线程库,其中我在不同的线程中调用sleep(3)。 我已经使用boost python为它写了python绑定。 现在它看起来像增强python搞乱睡眠(3)函数,因为它暂停整个python程序等待。boost python sleep wrapper导致整个python程序进入睡眠状态

请考虑我有这个boostmod.cpp文件

#include <boost/python.hpp> 
using namespace boost::python; 
BOOST_PYTHON_MODULE(boostmod) { 
    def("waiter",&::sleep); 
} 

(您可以使用编译:)

$ g++ -fPIC -shared boostmod.cpp `python-config --cflags --libs` -lboost_python -o boostmod.so 

这是一个Python测试文件threadtest.py:

import time,sys,threading,boostmod 
from ctypes import * 
if __name__ == '__main__': 
    libc = CDLL("libc.so.6") # this only works in linux 
    for n in range(5): 
     if sys.argv[1] == "boost": 
      # this is slow 
      threading.Thread(target=boostmod.waiter,args=(3,)).start() 
     elif sys.argv[1] == "native": 
      # this is fast 
      threading.Thread(target=time.sleep,args=(3,)).start() 
     elif sys.argv[1] == "ctypes": 
      # this is fast 
      threading.Thread(target=libc.sleep,args=(3,)).start() 

结果如下:

$ time python threadtest.py boost 
    real 0m15.030s 
    user 0m0.024s 
    sys  0m0.005s 
$ time python threadtest.py native 
    real 0m3.032s 
    user 0m0.027s 
    sys  0m0.003s 
$ time python threadtest.py ctypes 
    real 0m3.030s 
    user 0m0.022s 
    sys  0m0.008s 

如果你观察到的情况与:

$ watch -n1 ps -C python -L -o pid,tid,pcpu,state 

你可以看到,“本土”和“ctypes的”真正建立5个线程加,而“提升”的情况下仅具有一个主线程线。实际上,在“boost”情况下,“.start()”在“sleep()”函数中被阻塞。

回答

1

首先,我已经看到python中的time.sleep函数没有使用sleep(3) systemcall。它使用timing out call of select(2) on stdin(在函数“floatsleep”中),以便它可以被中断。

但是我也发现,如果你在wrapperPy_BEGIN_ALLOW_THREADSPy_END_ALLOW_THREADS围绕升压模块功能写这个现象似乎会消失。

所以这里是允许与sleep(3)调用多线程的新的动力模块代码:

#include <boost/python.hpp> 
using namespace boost::python; 
void waiter(int seconds) { 
    Py_BEGIN_ALLOW_THREADS 
    ::sleep(seconds); 
    Py_END_ALLOW_THREADS 
} 
BOOST_PYTHON_MODULE(boostmod) { 
    def("waiter",&::waiter); 
} 
相关问题