knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
shared_ptr.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of KnowRob, please consult
3  * https://github.com/knowrob/knowrob for license details.
4  */
5 
6 #include <knowrob/Logger.h>
7 #include <knowrob/ThreadPool.h>
8 #include <knowrob/integration/python/gil.h>
9 #include <knowrob/integration/python/converter/shared_ptr.h>
10 
11 #define KNOWROB_PY_USE_SHARED_PTR_DELETER_QUEUE
12 
14  void shared_ptr_deleter::operator()(void const *) {
15  // This is needed to release the Python GIL when the shared_ptr is deleted.
16  // Otherwise, if the shared_ptr is deleted in a C++ thread,
17  // Python will crash because the GIL is not acquired.
18  // There was also a debate about adding this to boost which was not really conclusive
19  // ite seems.
20  // @see https://github.com/boostorg/python/pull/11
21 
22 #ifdef KNOWROB_PY_USE_SHARED_PTR_DELETER_QUEUE
23  static knowrob::ThreadPool gil_pool(1);
24  // release the shared_ptr such that we can call reset in a worker thread
25  auto released_ptr = owner.release();
26  // a lambda worker that will lock the GIL and delete the pointer.
27  // note that calling reset in the current thread directly may cause deadlocks.
28  auto runner = std::make_shared<knowrob::ThreadPool::LambdaRunner>(
29  [released_ptr](const knowrob::ThreadPool::LambdaRunner::StopChecker &) {
31  handle<> ptr_handle(released_ptr);
32  ptr_handle.reset();
33  });
34  gil_pool.pushWork(runner, [](const std::exception &e) {
35  KB_WARN("an exception occurred when deleting ptr: {}.", e.what());
36  throw;
37  });
38 #else
40  owner.reset();
41 #endif
42  }
43 }
44 
45 namespace boost {
46  // This is needed for boost::python to work with std::shared_ptr.
47  // @see https://stackoverflow.com/questions/46435509/boostpython-stdshared-ptr-to-stdshared-ptr
48  template<class T>
49  T *get_pointer(std::shared_ptr<T> p) { return p.get(); }
50 }
#define KB_WARN
Definition: Logger.h:27
std::function< bool()> StopChecker
Definition: ThreadPool.h:152
void pushWork(const std::shared_ptr< ThreadPool::Runner > &goal, ThreadPool::ExceptionHandler exceptionHandler)
Definition: ThreadPool.cpp:70
T * get_pointer(std::shared_ptr< T > p)
Definition: shared_ptr.cpp:49