Skip to content

Commit 5278549

Browse files
committed
Use concurrency safe method for python initialization.
1 parent 0ef2199 commit 5278549

1 file changed

Lines changed: 13 additions & 13 deletions

File tree

  • pythonforandroid/bootstraps/common/build/jni/application/src

pythonforandroid/bootstraps/common/build/jni/application/src/start.c

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#error Python headers needed to compile C extensions, please install development version of Python.
66
#else
77

8+
#include <pthread.h>
89
#include <stdio.h>
910
#include <stdlib.h>
1011
#include <stdbool.h>
@@ -77,7 +78,17 @@ static int file_exists(const char *filename) {
7778
return 0;
7879
}
7980

80-
static int gil_init = 0; /* 1 when Python has been initialied/GIL created */
81+
static pthread_once_t pythonInitialized = PTHREAD_ONCE_INIT; /* Control when to initialize Python */
82+
83+
void initPython(void) {
84+
Py_Initialize();
85+
LOGP("Initialized python");
86+
/* ensure threads will work.
87+
*/
88+
LOGP("Calling init threads (unneeded for Python 3.7+)");
89+
PyEval_InitThreads();
90+
PyEval_SaveThread();
91+
}
8192

8293
static int run_python(int argc, char *argv[], bool call_exit, char* argument_name, char* argument_value) {
8394

@@ -196,18 +207,7 @@ static int run_python(int argc, char *argv[], bool call_exit, char* argument_nam
196207
" recipes should have this folder, should we expect a crash soon?");
197208
}
198209

199-
if (!gil_init) {
200-
gil_init = 1;
201-
Py_Initialize();
202-
LOGP("Initialized python");
203-
/* ensure threads will work.
204-
*/
205-
LOGP("Calling init threads (unneeded for Python 3.7+)");
206-
PyEval_InitThreads();
207-
PyEval_SaveThread();
208-
} else {
209-
LOGP("Python already initialized in this process");
210-
}
210+
pthread_once(&pythonInitialized, initPython);
211211

212212
/* Ensure that we are registering this thread against the GIL */
213213
PyGILState_STATE gstate;

0 commit comments

Comments
 (0)