How to set result of future\add to queue from another thread in Cython?
<p>I have C++ dll which works with multiple threads.
So I wrapped this library with Cython and created special receiver callback-function, which must adds some results to asyncio.Queue.</p>

<pre><code>cdef void __cdecl NewMessage(char* message) nogil:
</code></pre>

<p>I marked it as nogil, this callback calls from another thread.
In this callback I just use:</p>

<pre><code>with gil:
   print("hello")  # instead adding to Queue. print("hello") is more simple operation to demostrate problem
</code></pre>

<p>And got deadlock here. 
How to resolve it?</p>

<p>C++ callback declaration (header):</p>

<pre><code>typedef void (*receiver_t)(char*);
void SetReceiver(receiver_t new_rec);
</code></pre>

<p>cpp:</p>

<pre><code>static receiver_t receiver = nullptr;

void SetReceiver(receiver_t new_rec)
{
    printf("setted%i\n", (int)new_rec);
    a = 123;
    if (new_rec != nullptr)
        receiver = new_rec;
}
</code></pre>

<p>Cython code:</p>

<pre><code>cdef extern from "TeamSpeak3.h":
    ctypedef void (*receiver_t) (char*) nogil
    cdef void __cdecl SetReceiver(receiver_t new_rec) nogil

cdef void __cdecl NewMessage(char* message) nogil:
    with gil:
        print("hello")

SetReceiver(NewMessage)
</code></pre>

<p>Full code:
.h <a href="http://pastebin.com/ZTCjc6NA" rel="nofollow">http://pastebin.com/ZTCjc6NA</a></p>

<p>.cpp <a href="http://pastebin.com/MeygA8im" rel="nofollow">http://pastebin.com/MeygA8im</a></p>

<p>.pyx <a href="http://pastebin.com/k4X9c54P" rel="nofollow">http://pastebin.com/k4X9c54P</a></p>

<p>.py <a href="http://pastebin.com/1YV7tMiF" rel="nofollow">http://pastebin.com/1YV7tMiF</a></p>

<p>This is a bit of a guess but you probably have a Cython/C/C++ loop running that's holding the GIL and never releasing it. The callback is then forced for wait forever for it.</p>

<p>In normal Python code the GIL is released every few instructions if another thread is waiting for it. In Cython that doesn't happen automatically. One way to ensure that it does happen every so often is to to your loop:</p>

<pre><code>while True:
   # ... do stuff
   with nogil:
      pass
</code></pre>

<p>This ensures the GIL is released once per loop.</p>

<p>Unfortunately it's not obvious to me where you have your main loop. I wonder if it's inside <code>connect</code> in your <code>PyTeamSpeak3</code> class, and perhaps changing the definition of connect to:</p>

<pre><code>def connect(self):
    with nogil:
       self.thisptr.Connect()
</code></pre>

<p>might help?</p>

python c++ multithreading cython gil