Error in Python? threading.Thread.start () does not always return

I have a small Python script that (in my eyes) does it threading.Thread.start()behave unexpectedly, since it does not return immediately.

Inside the stream, I want to call a method from an object boost::pythonthat will not return immediately.

To do this, I wrap the object / method as follows:

import threading
import time
import my_boostpython_lib

my_cpp_object = my_boostpython_lib.my_cpp_class()

def some_fn():
    # has to be here - otherwise .start() does not return
    # time.sleep(1)  
    my_cpp_object.non_terminating_fn() # blocks

print("%x: 1" % threading.get_ident())
threading.Thread(target=some_fn).start()
print("%x: 2" % threading.get_ident())  # will not always be called!!

And everything works fine while I run the code up to my_cpp_object.non_terminating_fn() . If I do not, it .start()will block the same thing as the call .run().

Printing just a line before a function call is boost::pythonnot enough, but, for example, printing two lines or calling time.sleep()returns start()immediately as expected.

? ( sleep() boost::python)?

+4
1

( , /), Python, , , - Python GIL ( ).

non-Python my_cpp_object.non_terminating_fn() , GIL , , - .

time.sleep(1) , , my_cpp_object.non_terminating_fn(), , GIL .

boost::python , , , C/++, GIL, .

( ) ( boost:: python)

class scoped_gil_release {
public:
    inline scoped_gil_release() {
        m_thread_state = PyEval_SaveThread();
    }

    inline ~scoped_gil_release() {
        PyEval_RestoreThread(m_thread_state);
        m_thread_state = NULL;
    }

private:
    PyThreadState * m_thread_state;
};

int non_terminating_fn_wrapper() {
    scoped_gil_release scoped;
    return non_terminating_fn();
}
+3

Source: https://habr.com/ru/post/1598234/


All Articles