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>
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)24 void ExecuteCtxTlsDestructor(void* args)
25 {
26     auto ctx = static_cast<ExecuteCtx*>(args);
27     if (ctx) {
28         delete ctx;
29     }
30 }
31 
MakeExecuteCtxTlsKey()32 void MakeExecuteCtxTlsKey()
33 {
34     pthread_key_create(&g_executeCtxTlsKey, ExecuteCtxTlsDestructor);
35 }
36 }
37 
ExecuteCtx()38 ExecuteCtx::ExecuteCtx()
39 {
40     task = nullptr;
41     wn.weType = 2;
42     tid = syscall(SYS_gettid);
43 }
44 
~ExecuteCtx()45 ExecuteCtx::~ExecuteCtx()
46 {
47 }
48 
Cur()49 ExecuteCtx* ExecuteCtx::Cur()
50 {
51     ExecuteCtx* ctx = nullptr;
52     pthread_once(&g_executeCtxKeyOnce, MakeExecuteCtxTlsKey);
53 
54     void *curTls = pthread_getspecific(g_executeCtxTlsKey);
55     if (curTls != nullptr) {
56         ctx = reinterpret_cast<ExecuteCtx *>(curTls);
57     } else {
58         ctx = new (std::nothrow) ExecuteCtx();
59         pthread_setspecific(g_executeCtxTlsKey, ctx);
60     }
61     return ctx;
62 }
63 
64 } // namespace ffrt