event_pool.cpp 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/**
 * \file imperative/src/impl/event_pool.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

12
#include "./event_pool.h"
13 14 15
#include <memory>

#include "megbrain/imperative/resource_manager.h"
16 17 18 19 20 21 22

namespace mgb {
namespace imperative {

EventPool::EventPool(size_t flags) : m_flags{flags} {}

EventPool& EventPool::with_timer() {
23 24 25 26 27 28
    static auto* sm_pool =
            ResourceManager::create_global<CompNodeDependentResource<EventPool>>([] {
                return std::unique_ptr<EventPool>(
                        new EventPool(CompNode::Event::NEED_TIMER));
            });
    return **sm_pool;
29 30
}
EventPool& EventPool::without_timer() {
31 32 33 34
    static auto* sm_pool =
            ResourceManager::create_global<CompNodeDependentResource<EventPool>>(
                    [] { return std::unique_ptr<EventPool>(new EventPool()); });
    return **sm_pool;
35 36 37 38 39 40 41 42
}
CompNode::Event* EventPool::alloc(CompNode cn) {
    CompNode::EventPool* pool;
    {
        MGB_LOCK_GUARD(m_lock);
        auto iter = m_cn2pool.find(cn);
        if (iter == m_cn2pool.end()) {
            iter = m_cn2pool
M
Megvii Engine Team 已提交
43 44 45
                           .emplace(
                                   std::piecewise_construct, std::forward_as_tuple(cn),
                                   std::forward_as_tuple(cn, m_flags))
46 47 48 49 50 51 52 53
                           .first;
        }
        pool = &iter->second;
    }
    return pool->alloc();
}
std::shared_ptr<CompNode::Event> EventPool::alloc_shared(CompNode cn) {
    auto* raw_event = alloc(cn);
M
Megvii Engine Team 已提交
54
    return {raw_event, [this](CompNode::Event* event) { this->free(event); }};
55 56 57 58 59 60 61 62 63 64 65 66 67 68
}
void EventPool::free(CompNode::Event* event) {
    CompNode::EventPool* pool;
    {
        MGB_LOCK_GUARD(m_lock);
        pool = &m_cn2pool.at(event->comp_node());
    }
    pool->free(event);
}
std::shared_ptr<void> EventPool::on_comp_node_finalize() {
    MGB_LOCK_GUARD(m_lock);
    for (auto&& i : m_cn2pool) {
        i.second.assert_all_freed();
    }
69
    m_cn2pool.clear();
70 71 72 73 74 75 76 77 78 79
    return {};
}
EventPool::~EventPool() {
    for (auto&& i : m_cn2pool) {
        i.second.assert_all_freed();
    }
}

}  // namespace imperative
}  // namespace mgb