PyEval_InitThreads in Python 3: How/when to call it? (the saga continues ad nauseam)

前端 未结 7 1082
别那么骄傲
别那么骄傲 2020-11-27 03:06

Basically there seems to be massive confusion/ambiguity over when exactly PyEval_InitThreads() is supposed to be called, and what accompanying API

7条回答
  •  盖世英雄少女心
    2020-11-27 03:51

    There are two methods of multi threading while executing C/Python API.

    1.Execution of different threads with same interpreter - We can execute a Python interpreter and share the same interpreter over the different threads.

    The coding will be as follows.

    main(){     
    //initialize Python
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
        "print 'In Main, Today is',ctime(time())\n");
    
    //to Initialize and acquire the global interpreter lock
    PyEval_InitThreads();
    
    //release the lock  
    PyThreadState *_save;
    _save = PyEval_SaveThread();
    
    // Create threads.
    for (int i = 0; i
    1. Another method is that, we can execute a Python interpreter in the main thread and, to each thread we can give its own sub interpreter. Thus every thread runs with its own separate , independent versions of all imported modules, including the fundamental modules - builtins, __main__ and sys.

    The code is as follows

    int main()
    {
    
    // Initialize the main interpreter
    Py_Initialize();
    // Initialize and acquire the global interpreter lock
    PyEval_InitThreads();
    // Release the lock     
    PyThreadState *_save;
    _save = PyEval_SaveThread();
    
    
    // create threads
    for (int i = 0; i

    It is necessary to note that the Global Interpreter Lock still persists and, in spite of giving individual interpreters to each thread, when it comes to python execution, we can still execute only one thread at a time. GIL is UNIQUE to PROCESS, so in spite of providing unique sub interpreter to each thread, we cannot have simultaneous execution of threads

    Sources: Executing a Python interpreter in the main thread and, to each thread we can give its own sub interpreter

    Multi threading tutorial (msdn)

提交回复
热议问题