1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15#include "execute_ctx.h" 16#include <sys/syscall.h> 17#include <unistd.h> 18pthread_key_t g_executeCtxTlsKey = 0; 19pthread_once_t g_executeCtxKeyOnce = PTHREAD_ONCE_INIT; 20 21namespace ffrt { 22namespace { 23void ExecuteCtxTlsDestructor(void* args) 24{ 25 auto ctx = static_cast<ExecuteCtx*>(args); 26 if (ctx) { 27 delete ctx; 28 } 29} 30 31void MakeExecuteCtxTlsKey() 32{ 33 pthread_key_create(&g_executeCtxTlsKey, ExecuteCtxTlsDestructor); 34} 35} // namespace 36 37ExecuteCtx::ExecuteCtx() 38{ 39 task = nullptr; 40 wn.weType = 2; 41 tid = syscall(SYS_gettid); 42} 43 44ExecuteCtx::~ExecuteCtx() 45{ 46} 47 48ExecuteCtx* ExecuteCtx::Cur() 49{ 50 ExecuteCtx* ctx = nullptr; 51 pthread_once(&g_executeCtxKeyOnce, MakeExecuteCtxTlsKey); 52 53 void *curTls = pthread_getspecific(g_executeCtxTlsKey); 54 if (curTls != nullptr) { 55 ctx = reinterpret_cast<ExecuteCtx *>(curTls); 56 } else { 57 ctx = new (std::nothrow) ExecuteCtx(); 58 pthread_setspecific(g_executeCtxTlsKey, ctx); 59 } 60 return ctx; 61} 62 63} // namespace ffrt