I have a Python app that calls a C++ boost python library and it all works. However, I have a callback C++ to Python scenario where C++ from a boost thread calls python and I get an access violation on the C++ side. If I do exactly the same callback using the python thread it works perfectly. Therefore I suspect that I can not simply callback Python from C++ using a boost thread but need to do something extra for it to work?
How to call Python from a boost thread?
1.8k Views Asked by SkyWalker At
1
There are 1 best solutions below
Related Questions in PYTHON
- How to store a date/time in sqlite (or something similar to a date)
- Instagrapi recently showing HTTPError and UnknownError
- How to Retrieve Data from an MySQL Database and Display it in a GUI?
- How to create a regular expression to partition a string that terminates in either ": 45" or ",", without the ": "
- Python Geopandas unable to convert latitude longitude to points
- Influence of Unused FFN on Model Accuracy in PyTorch
- Seeking Python Libraries for Removing Extraneous Characters and Spaces in Text
- Writes to child subprocess.Popen.stdin don't work from within process group?
- Conda has two different python binarys (python and python3) with the same version for a single environment. Why?
- Problem with add new attribute in table with BOTO3 on python
- Can't install packages in python conda environment
- Setting diagonal of a matrix to zero
- List of numbers converted to list of strings to iterate over it. But receiving TypeError messages
- Basic Python Question: Shortening If Statements
- Python and regex, can't understand why some words are left out of the match
Related Questions in C++
- How to immediately apply DISPLAYCONFIG_SCALING display scaling mode with SetDisplayConfig and DISPLAYCONFIG_PATH_TARGET_INFO
- Why can't I use templates members in its specialization?
- How to fix "Access violation executing location" when using GLFW and GLAD
- Dynamic array of structures in C++/ cannot fill a dynamic array of doubles in structure from dynamic array of structures
- How do I apply the interface concept with the base-class in design?
- File refuses to compile std::erase() even if using -std=g++23
- How can I do a successful map when the number of elements to be mapped is not consistent in Thrust C++
- Can std::bit_cast be applied to an empty object?
- Unexpected inter-thread happens-before relationships from relaxed memory ordering
- How i can move element of dynamic vector in argument of function push_back for dynamic vector
- Brick Breaker Ball Bounce
- Thread-safe lock-free min where both operands can change c++
- Watchdog Timer Reset on ESP32 using Webservers
- How to solve compiler error: no matching function for call to 'dmhFS::dmhFS()' in my case?
- Conda CMAKE CXX Compiler error while compiling Pytorch
Related Questions in MULTITHREADING
- How can I outsource worker processes within a for loop?
- OpenMP & oneTbb difference
- Receiving Notifications for Individual Task Completion OmniThreadLibrary Parallel.ForEach
- C++ error: no matching member function for call to 'enqueue' futures.emplace_back(TP.enqueue(sum_plus_one, x, &M));
- How can I create a thread in Haskell that will restart if it gets killed due to any reason?
- Qt: running callback in the main thread from the worker thread
- Using `static` on a AVX2 counter function increases performance ~10x in MT environment without any change in Compiler optimizations
- Heap sort with multithreading
- windows multithreading CreateMutex
- The problem of "fine-grained locks and two-phase locking algorithm"
- OpenMP multi-threading not working if OpenMPI set to use one or two MPI processor
- WPF Windows Initializing is locking the separated thread in .Net 8
- TCP Client Losing Connection When Writing Data
- vc++ thread constructor throwing compiler error c2672
- ASP.NET Core 6 Web API : best way to pause before resending email
Related Questions in BOOST-PYTHON
- How to bind boost::iterator_range of Iterator class using Boost Python
- How to use boost::python raw_function without getting warning C4267?
- Pybind11/Nanobind: How to return class object and use methods from Python. How can I cast the C++ object to something whose methods I can use in Py
- Boost Python: exposing std::list of enums
- Boost Python : exposing optional list of enums
- How to declare a C++ function that can take any python iterable?
- to_python_converter , is by value needed?
- python::boost modules over aliases : RecursionError
- How to make python3 import examine .so and ...-g.so as well?
- Boost/python.hpp is not correctly linked when using CMake and Conan
- Linking error using boost-python library macOS m2
- How to build libboost-python.so in Boost 1.74
- Boost Python Converter for Custom Bool Type
- Linking error trying to make module with boost python
- When compiling Boost.Python in debug mode, I encountered an error indicating the absence of python.lib
Related Questions in BOOST-THREAD
- Boost 1.81.0 (chrono and thread) library compilation is failing with Sun Studio 12.5
- c++ boost.thread executable not running
- Compile error while using boost::concept_check to check a template argument
- 'MT_StaticRelease' not match 'MD_DynamicRelease' using cmake vcpkg
- Thread-ID is always the same in my boost::asio::thread_pool
- boost::bind member function as argument inside its own member function
- Passing move-only function arguments to boost::thread constructor
- How to create 3 threads of parallel execution using boost library in C++ (in Visual Studio 2019)?
- boost thread::join() in a destructor is warned by a static analysis tool
- dead-lock with condition_variable
- boost::thread vs std::thread vs pthread
- Linking Boost Thread: No rule to make target ".../libpthread.so"
- passing std::future to a boost::thread vs a std::thread
- "Undefined symbols for architecture x86_64:" Boost 1.73.0 Clion MacOS
- Thread synchronization in C++, with less overhead
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
The most likely culprit is that the Global Interpreter Lock (GIL) is not being held by a thread when it is invoking Python code, resulting in undefined behavior. Verify all paths that make direct or indirect Python calls, acquire the GIL before invoking Python code.
The GIL is a mutex around the CPython interpreter. This mutex prevents parallel operations to be performed on Python objects. Thus, at any point in time, a max of one thread, the one that has acquired the GIL, is allowed to perform operations on Python objects. When multiple threads are present, invoking Python code whilst not holding the GIL results in undefined behavior.
C or C++ threads are sometimes referred to as alien threads in the Python documentation. The Python interpreter has no ability to control the alien thread. Therefore, alien threads are responsible for managing the GIL to permit concurrent or parallel execution with Python threads. One must meticulously consider:
One solution is to wrap Python callbacks with a custom type that is aware of GIL management.
Using a RAII-style class to manage the GIL provides an elegant exception-safe solution. For example, with the following
with_gilclass, when awith_gilobject is created, the calling thread acquires the GIL. When thewith_gilobject is destructed, it restores the GIL state.And its usage:
With being able to manage the GIL via
with_gil, the next step is to create a functor that properly manages the GIL. The followingpy_callableclass will wrap aboost::python::objectand acquire the GIL for all paths in which Python code is invoked:By managing the
boost::python::objecton the free-space, one can freely copy theshared_ptrwithout having to hold the GIL. This allows for us to safely use the default generated copy-constructor, assignment operator, destructor, etc.One would use the
py_callableas follows:Here is a complete example demonstrating having a Python extension invoke a Python object as a callback from a C++ thread:
Interactive usage: