MCPcopy Create free account
hub / github.com/PierreGode/Ragnar / _cffi_start_python

Function _cffi_start_python

pager_lib/cffi/_embedding.h:422–502  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

420
421#ifdef __GNUC__
422__attribute__((noinline))
423#endif
424static _cffi_call_python_fnptr _cffi_start_python(void)
425{
426 /* Delicate logic to initialize Python. This function can be
427 called multiple times concurrently, e.g. when the process calls
428 its first ``extern "Python"`` functions in multiple threads at
429 once. It can also be called recursively, in which case we must
430 ignore it. We also have to consider what occurs if several
431 different cffi-based extensions reach this code in parallel
432 threads---it is a different copy of the code, then, and we
433 can't have any shared global variable unless it comes from
434 'libpythonX.Y.so'.
435
436 Idea:
437
438 * _cffi_carefully_make_gil(): "carefully" call
439 PyEval_InitThreads() (possibly with Py_InitializeEx() first).
440
441 * then we use a (local) custom lock to make sure that a call to this
442 cffi-based extension will wait if another call to the *same*
443 extension is running the initialization in another thread.
444 It is reentrant, so that a recursive call will not block, but
445 only one from a different thread.
446
447 * then we grab the GIL and (Python 2) we call Py_InitializeEx().
448 At this point, concurrent calls to Py_InitializeEx() are not
449 possible: we have the GIL.
450
451 * do the rest of the specific initialization, which may
452 temporarily release the GIL but not the custom lock.
453 Only release the custom lock when we are done.
454 */
455 static char called = 0;
456
457 if (_cffi_carefully_make_gil() != 0)
458 return NULL;
459
460 _cffi_acquire_reentrant_mutex();
461
462 /* Here the GIL exists, but we don't have it. We're only protected
463 from concurrency by the reentrant mutex. */
464
465 /* This file only initializes the embedded module once, the first
466 time this is called, even if there are subinterpreters. */
467 if (!called) {
468 called = 1; /* invoke _cffi_initialize_python() only once,
469 but don't set '_cffi_call_python' right now,
470 otherwise concurrent threads won't call
471 this function at all (we need them to wait) */
472 if (_cffi_initialize_python() == 0) {
473 /* now initialization is finished. Switch to the fast-path. */
474
475 /* We would like nobody to see the new value of
476 '_cffi_call_python' without also seeing the rest of the
477 data initialized. However, this is not possible. But
478 the new value of '_cffi_call_python' is the function
479 'cffi_call_python()' from _cffi_backend. So: */

Callers 2

cffi_start_pythonFunction · 0.85

Calls 4

_cffi_carefully_make_gilFunction · 0.85
_cffi_initialize_pythonFunction · 0.85

Tested by

no test coverage detected