title: Segmentation fault when using ctypes and threading
body: <p>I wrote a Python wrapper for a C library using <code>ctypes</code>. Everything worked fine, until I tried it with the <code>threading</code> module.</p>
  
  <p>Here is a small example to reproduce it:</p>
  
  <h1>foo.c</h1>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;assert.h&gt;
  
  char *foo_init() {
      char *result = (char*)malloc(sizeof(char));
      assert(result);
      return result;
  }
  
  char foo_get(const char* p) {
      return *p;
  }
  
  void foo_set(char *p, char value) {
      *p = value;
  }
  
  void foo_del(char *p) {
      free(p);
  }
  </code></pre>
  
  <h1>foo.py</h1>
  
  <pre><code>import threading
  import ctypes
  libfoo=ctypes.CDLL('foo.so')
  
  libfoo.foo_init.restype = ctypes.c_void_p
  libfoo.foo_get.restype = ctypes.c_char
  
  class Foo:
      def __init__(self):
          self.__obj__ = libfoo.foo_init()
  
      def get(self):
          return libfoo.foo_get(self.__obj__)
  
      def set(self, value):
          libfoo.foo_set(self.__obj__, ctypes.c_char(value))
  
      def __del__(self):
          libfoo.foo_del(self.__obj__)
  
  x = Foo()
  x.set(b'x')
  print(x.get())
  
  def compute():
      y = Foo()
      y.set(b'y')
      print(y.get())
  
  t = threading.Thread(target=compute)
  t.start()
  t.join()
  </code></pre>
  
  <p>Compilation:</p>
  
  <pre><code>gcc -Wall -shared -o foo.so -fPIC foo.c
  </code></pre>
  
  <p>Execution:</p>
  
  <pre><code>export LD_LIBRARY_PATH=.
  python3 foo.py
  </code></pre>
  
  <p>Result:</p>
  
  <pre><code>b'x'
  [1]    8627 segmentation fault  python3 foo.py
  </code></pre>
  
  <p>We see here that <code>x.get()</code> is correctly printed whereas <code>y.get()</code> does a segmentation fault. Thus, it seems that there is a problem linked to <code>ctypes</code> and <code>threading</code>.</p>
  
  <p>Note that if I move the initialization of <code>y</code> outside of the <code>compute</code> function, then the program exits normally.</p>
  
  <p>Moreover, each of the functions which manipulate the pointer produce a segmentation fault (e.g. if I just keep the <code>__init__</code> and <code>__del__</code> functions, there is still a crash).</p>
  
  <p>Any idea on how to fix this?</p>