title: Boost.Python: Wrap functions to release the GIL
body: <p>I am currently working with Boost.Python and would like some help to solve a tricky problem.</p>
  
  <p><strong>Context</strong></p>
  
  <p>When a C++ method/function is exposed to Python, it needs to release the GIL (Global Interpreter Lock) to let other threads use the interpreter. This way, when the python code calls a C++ function, the interpreter can be used by other threads.
  For now, each C++ function looks like this:</p>
  
  <pre><code>// module.cpp
  int myfunction(std::string question)
  {
      ReleaseGIL unlockGIL;
      return 42;
  }
  </code></pre>
  
  <p>To pass it to boost python, I do:</p>
  
  <pre><code>// python_exposure.cpp
  BOOST_PYTHON_MODULE(PythonModule)
  {
      def("myfunction", &amp;myfunction);
  }
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>This scheme works fine, however it implies that <code>module.cpp</code> depends on <code>Boost.Python</code> for no good reason. Ideally, only <code>python_exposure.cpp</code> should depend on <code>Boost.Python</code>.</p>
  
  <p><strong>Solution?</strong></p>
  
  <p>My idea was to play with <code>Boost.Function</code> to wrap the function calls like this:</p>
  
  <pre><code>// python_exposure.cpp
  BOOST_PYTHON_MODULE(PythonModule)
  {
      def("myfunction", wrap(&amp;myfunction));
  }
  </code></pre>
  
  <p>Here <code>wrap</code> would be in charge of unlocking the GIL during the call to <code>myfunction</code>. The problem with this method is that <code>wrap</code> needs to have the same signature as <code>myfunction</code> which would pretty much mean re-implementing <code>Boost.Function</code>...</p>
  
  <p>I would be very thankful if someone had any suggestion to this problem.</p>