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 "sched/execute_ctx.h" 16 #include <sys/syscall.h> 17 #include <unistd.h> 18 #include <pthread.h> 19 20 pthread_key_t g_executeCtxTlsKey = 0; 21 pthread_once_t g_executeCtxKeyOnce = PTHREAD_ONCE_INIT; 22 namespace ffrt { 23 namespace { ExecuteCtxTlsDestructor(void * args)24void ExecuteCtxTlsDestructor(void* args) 25 { 26 auto ctx = static_cast<ExecuteCtx*>(args); 27 if (ctx) { 28 delete ctx; 29 } 30 } 31 MakeExecuteCtxTlsKey()32void MakeExecuteCtxTlsKey() 33 { 34 pthread_key_create(&g_executeCtxTlsKey, ExecuteCtxTlsDestructor); 35 } 36 } 37 ExecuteCtx()38ExecuteCtx::ExecuteCtx() 39 { 40 task = nullptr; 41 tid = syscall(SYS_gettid); 42 } 43 ~ExecuteCtx()44ExecuteCtx::~ExecuteCtx() 45 { 46 } 47 Cur(bool init)48ExecuteCtx* ExecuteCtx::Cur(bool init) 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 if (init) { 57 ctx = new ExecuteCtx(); 58 pthread_setspecific(g_executeCtxTlsKey, ctx); 59 } 60 return ctx; 61 } 62 63 } // namespace ffrt