MNN/express/ExecutorScope.cpp

73 lines
1.8 KiB
C++
Raw Normal View History

2020-11-05 16:41:56 +08:00
//
// ExecutorScope.cpp
// MNN
//
// Created by MNN on 2020/10/26.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include <thread>
2021-02-07 10:45:07 +08:00
#include <mutex>
2020-11-05 16:41:56 +08:00
#include <MNN/expr/Executor.hpp>
#include <MNN/expr/Scope.hpp>
#include <MNN/expr/ExecutorScope.hpp>
namespace MNN {
namespace Express {
typedef std::shared_ptr<Express::Executor> ExecutorRef;
2022-05-06 19:51:20 +08:00
#if TARGET_OS_IPHONE
#include <pthread.h>
static pthread_key_t gKey;
static std::once_flag gInitFlag;
#else
2021-02-07 10:45:07 +08:00
thread_local static std::once_flag gInitFlag;
thread_local static Scope<ExecutorRef>* g_executor_scope = nullptr;
2020-11-05 16:41:56 +08:00
#endif
2021-02-07 10:45:07 +08:00
static Scope<ExecutorRef>* _getGlobalScope() {
std::call_once(gInitFlag,
[&]() {
2022-05-06 19:51:20 +08:00
#if TARGET_OS_IPHONE
pthread_key_create(&gKey, NULL);
#else
2023-08-21 14:51:54 +08:00
thread_local static Scope<ExecutorRef> initValue;
g_executor_scope = &initValue;
2022-05-06 19:51:20 +08:00
#endif
2021-02-07 10:45:07 +08:00
});
2022-05-06 19:51:20 +08:00
#if TARGET_OS_IPHONE
Scope<ExecutorRef>* scope = static_cast<Scope<ExecutorRef>*>(pthread_getspecific(gKey));
if (!scope) {
scope = new Scope<ExecutorRef>;
pthread_setspecific(gKey, static_cast<void*>(scope));
}
return scope;
#else
2021-02-07 10:45:07 +08:00
return g_executor_scope;
2022-05-06 19:51:20 +08:00
#endif
2021-02-07 10:45:07 +08:00
}
2020-11-05 16:41:56 +08:00
ExecutorScope::ExecutorScope(const std::shared_ptr<Executor>& current) {
2021-02-07 10:45:07 +08:00
_getGlobalScope()->EnterScope(current);
2020-11-05 16:41:56 +08:00
}
ExecutorScope::ExecutorScope(const std::string& scope_name,
const std::shared_ptr<Executor>& current) {
2021-02-07 10:45:07 +08:00
_getGlobalScope()->EnterScope(scope_name, current);
2020-11-05 16:41:56 +08:00
}
ExecutorScope::~ExecutorScope() {
2021-02-07 10:45:07 +08:00
_getGlobalScope()->ExitScope();
2020-11-05 16:41:56 +08:00
}
const std::shared_ptr<Executor> ExecutorScope::Current() {
2021-04-28 18:02:10 +08:00
auto exe = _getGlobalScope()->Content();
if (exe) {
return exe;
2020-11-05 16:41:56 +08:00
}
return Executor::getGlobalExecutor();
}
} // namespace Express
} // namespace MNN