Book Image

Learning Cython Programming (Second Edition) - Second Edition

By : Philip Herron
Book Image

Learning Cython Programming (Second Edition) - Second Edition

By: Philip Herron

Overview of this book

Cython is a hybrid programming language used to write C extensions for Python language. Combining the practicality of Python and speed and ease of the C language it’s an exciting language worth learning if you want to build fast applications with ease. This new edition of Learning Cython Programming shows you how to get started, taking you through the fundamentals so you can begin to experience its unique powers. You’ll find out how to get set up, before exploring the relationship between Python and Cython. You’ll also look at debugging Cython, before moving on to C++ constructs, Caveat on C++ usage, Python threading and GIL in Cython. Finally, you’ll learn object initialization and compile time, and gain a deeper insight into Python 3, which will help you not only become a confident Cython developer, but a much more fluent Python developer too.
Table of Contents (14 chapters)
Learning Cython Programming Second Edition
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface
Index

Caveat on GIL


There is a caveat to remember when using gil. In our callbacks, we need to acquire the GIL on each callback before we call any Python code; otherwise, we will segfault and get really confused. So, if you look into each of the libevent callbacks when calling the Cython functions, you have the following:

 PyGILState_STATE gilstate_save = PyGILState_Ensure();
 readcb (client, (char *)data);
 PyGILState_Release(gilstate_save);

Notice that this is also called on the other two callbacks—firstly on the discb callback:

  PyGILState_STATE gilstate_save = PyGILState_Ensure();
  discb (client, NULL);
  PyGILState_Release(gilstate_save);

Finally, on the connect callback, we must be a little safer and call it this way:

 PyGILState_STATE gilstate_save = PyGILState_Ensure();
  if (!conncb (NULL, inet_ntoa (client_addr.sin_addr)))
    {
…
    }
 else
    close (client_fd);
  PyGILState_Release(gilstate_save);

We have to do this since we executed this with nogil from Cython. We need to acquire gil...