| 86 | } |
| 87 | |
| 88 | FrameInfoCache* FrameInfoCache::get_instance() { |
| 89 | mgb_assert(support_tss); |
| 90 | constexpr int max_cache_size = 10; |
| 91 | static FrameInfoCache caches[max_cache_size]; |
| 92 | static uintptr_t tid = 1; |
| 93 | static std::list<std::pair<uintptr_t, FrameInfoCache*>> cache_list; |
| 94 | static std::unordered_map<uintptr_t, decltype(cache_list)::iterator> kv_map; |
| 95 | auto get_cache = [](uintptr_t key) { |
| 96 | if (kv_map.find(key) != kv_map.end()) { |
| 97 | auto it = kv_map[key]; |
| 98 | auto rst = it->second; |
| 99 | if (it != cache_list.begin()) { |
| 100 | cache_list.push_front(*it); |
| 101 | cache_list.erase(it); |
| 102 | kv_map[key] = cache_list.begin(); |
| 103 | } |
| 104 | return rst; |
| 105 | } |
| 106 | if (cache_list.size() < max_cache_size) { |
| 107 | auto* rst = &caches[key % max_cache_size]; |
| 108 | cache_list.emplace_front(key, rst); |
| 109 | kv_map[key] = cache_list.begin(); |
| 110 | return rst; |
| 111 | } else { |
| 112 | auto it = --cache_list.end(); |
| 113 | auto empty_cache = *it; |
| 114 | cache_list.erase(it); |
| 115 | empty_cache.second->stack_cache.clear(); |
| 116 | cache_list.push_front(empty_cache); |
| 117 | kv_map[key] = cache_list.begin(); |
| 118 | return empty_cache.second; |
| 119 | } |
| 120 | }; |
| 121 | #if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 6 |
| 122 | auto* id = PyThread_tss_get(&tss_key); |
| 123 | if (id == NULL) { |
| 124 | mgb_assert(PyThread_tss_set(&tss_key, (void*)tid) == 0); |
| 125 | return get_cache(tid++); |
| 126 | } else { |
| 127 | auto cache_tid = (uintptr_t)id; |
| 128 | return get_cache(cache_tid); |
| 129 | } |
| 130 | #else |
| 131 | auto* id = PyThread_get_key_value(tss_key); |
| 132 | if (id == NULL) { |
| 133 | mgb_assert(PyThread_set_key_value(tss_key, (void*)tid) == 0); |
| 134 | return get_cache(tid++); |
| 135 | } else { |
| 136 | auto cache_tid = (uintptr_t)id; |
| 137 | return get_cache(cache_tid); |
| 138 | } |
| 139 | #endif |
| 140 | } |
| 141 | |
| 142 | void FrameInfoCache::update_cache( |
| 143 | int key, |