title: Embedding a Python interpreter in a multi-threaded C++ program with pybind11
body: <p>I'm trying to use <a href="https://pybind11.readthedocs.io/en/stable/" rel="nofollow noreferrer">pybind11</a> in order to make a 3rd party C++ library call a Python method. The library is multithreaded, and each thread creates a Python object, and then does numerous calls to the object's methods.</p>
  <p>My problem is that the call to <code>py::gil_scoped_acquire acquire;</code> deadlocks. A minimal code which reproduces the problem is given below. What am I doing wrong?</p>
  <pre><code>// main.cpp
  class Wrapper
  {
  public:
    Wrapper()
    {
      py::gil_scoped_acquire acquire;
      auto obj = py::module::import(&quot;main&quot;).attr(&quot;PythonClass&quot;)();
      _get_x = obj.attr(&quot;get_x&quot;);
      _set_x = obj.attr(&quot;set_x&quot;);
    }
    
    int get_x() 
    {
      py::gil_scoped_acquire acquire;
      return _get_x().cast&lt;int&gt;();
    }
  
    void set_x(int x)
    {
      py::gil_scoped_acquire acquire;
      _set_x(x);
    }
  
  private:
    py::object _get_x;
    py::object _set_x;
  };
  
  
  void thread_func()
  {
    Wrapper w;
  
    for (int i = 0; i &lt; 10; i++)
    {
      w.set_x(i);
      std::cout &lt;&lt; &quot;thread: &quot; &lt;&lt; std::this_thread::get_id() &lt;&lt; &quot; w.get_x(): &quot; &lt;&lt; w.get_x() &lt;&lt; std::endl;
      std::this_thread::sleep_for(100ms);    
    }
  }
  
  int main() {
    py::scoped_interpreter python;
    
    std::vector&lt;std::thread&gt; threads;
  
    for (int i = 0; i &lt; 5; ++i)
      threads.push_back(std::thread(thread_func));
  
    for (auto&amp; t : threads)
      t.join();
  
    return 0;
  }
  </code></pre>
  <p>and the Python code:</p>
  <pre><code>// main.py
  class PythonClass:
      def __init__(self):
          self._x = 0
  
      def get_x(self):
          return self._x
  
      def set_x(self, x):
          self._x = x
  </code></pre>
  <p>Related questions can be found <a href="https://stackoverflow.com/questions/4153140/synchronizing-embedded-python-in-multi-threaded-program">here</a> and <a href="https://stackoverflow.com/questions/64429383/embed-python-c-api-in-a-multi-threading-c-program">here</a>, but did not help me solve the problem.</p>