Automatic Differentiation
 
Loading...
Searching...
No Matches
init_chainablestack.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP
2#define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP
3
5
6#include <tbb/task_scheduler_observer.h>
7
8#include <mutex>
9#include <unordered_map>
10#include <utility>
11#include <thread>
12#include <tuple>
13
14namespace stan {
15namespace math {
16
27class ad_tape_observer final : public tbb::task_scheduler_observer {
28 using stack_ptr = std::unique_ptr<ChainableStack>;
29 using ad_map = std::unordered_map<std::thread::id, stack_ptr>;
30
31 public:
32 ad_tape_observer() : tbb::task_scheduler_observer(), thread_tape_map_() {
33 on_scheduler_entry(true); // register current process
34 observe(true); // activates the observer
35 }
36
37 ~ad_tape_observer() { observe(false); }
38
39 void on_scheduler_entry(bool worker) {
40 std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
41 const std::thread::id thread_id = std::this_thread::get_id();
42 if (thread_tape_map_.find(thread_id) == thread_tape_map_.end()) {
43 ad_map::iterator insert_elem;
44 bool status = false;
45 std::tie(insert_elem, status)
46 = thread_tape_map_.emplace(ad_map::value_type{thread_id, nullptr});
47 insert_elem->second = std::make_unique<ChainableStack>();
48 }
49 }
50
51 void on_scheduler_exit(bool worker) {
52 std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
53 auto elem = thread_tape_map_.find(std::this_thread::get_id());
54 if (elem != thread_tape_map_.end()) {
55 thread_tape_map_.erase(elem);
56 }
57 }
58
59 private:
62};
63
64namespace {
65
66ad_tape_observer global_observer;
67
68} // namespace
69} // namespace math
70} // namespace stan
71
72#endif
std::unordered_map< std::thread::id, stack_ptr > ad_map
std::unique_ptr< ChainableStack > stack_ptr
TBB observer object which is a callback hook called whenever the TBB scheduler adds a new thread to t...
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...