1 /*
2 * Copyright (c) 2021 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
16 #include "thread_ex.h"
17 #include <sys/resource.h>
18 #include <sys/prctl.h>
19 #include <iostream>
20 #include "utils_log.h"
21
22 namespace OHOS {
23 using ThreadFunc = int (*)(void*);
24 using PThreadRoutine = void* (*) (void*);
25
26 struct ThreadParam {
27 ThreadFunc startRoutine;
28 void* args;
29 int priority;
30 std::string name;
31
32 // prctl only support set the name of the calling process.
proxyOHOS::ThreadParam33 static int proxy(const ThreadParam* t)
34 {
35 if (t == nullptr) {
36 UTILS_LOGE("invalid param.");
37 return -1;
38 }
39 ThreadFunc f = t->startRoutine;
40 void* userData = t->args;
41 int prio = t->priority;
42 std::string threadName = t->name;
43
44 delete t;
45
46 // set thread priority
47 (void)setpriority(PRIO_PROCESS, 0, prio);
48
49 // set thread name
50 if (!threadName.empty()) {
51 prctl(PR_SET_NAME, threadName.substr(0, MAX_THREAD_NAME_LEN).c_str(), 0, 0, 0);
52 }
53
54 return f(userData);
55 }
56 };
57
CreatePThread(ThreadParam & para,size_t stackSize,pthread_t * threadId)58 bool CreatePThread(ThreadParam& para, size_t stackSize, pthread_t *threadId)
59
60 {
61 pthread_attr_t attr;
62 pthread_attr_init(&attr);
63
64 // create thread as "detached", so it cleans up after itself.
65 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
66
67 auto t = new ThreadParam; // t would be delete in ThreadParam::proxy
68 t->startRoutine = para.startRoutine;
69 t->args = para.args;
70 t->priority = para.priority;
71 t->name = para.name;
72
73 para.startRoutine = (ThreadFunc)&ThreadParam::proxy;
74 para.args = t;
75
76 if (stackSize) {
77 pthread_attr_setstacksize(&attr, stackSize);
78 }
79
80 errno = 0;
81 pthread_t thread;
82 int result = pthread_create(&thread, &attr, (PThreadRoutine)para.startRoutine, para.args);
83 pthread_attr_destroy(&attr);
84
85 if (result != 0) {
86 return false;
87 }
88
89 if (threadId != NULL) {
90 *threadId = thread;
91 }
92
93 return true;
94 }
95
Thread()96 Thread::Thread()
97 : thread_(INVALID_PTHREAD_T), status_(ThreadStatus::OK), exitPending_(false), running_(false)
98 {
99 }
100
~Thread()101 Thread::~Thread()
102 {
103 }
104
Start(const std::string & name,int32_t priority,size_t stack)105 ThreadStatus Thread::Start(const std::string& name, int32_t priority, size_t stack)
106 {
107 std::lock_guard<std::mutex> lk(lock_);
108 if (running_) {
109 // already started
110 return ThreadStatus::INVALID_OPERATION;
111 }
112
113 status_ = ThreadStatus::OK;
114 exitPending_ = false;
115 thread_ = INVALID_PTHREAD_T;
116 running_ = true;
117
118 ThreadParam para;
119 para.startRoutine = ThreadStart;
120 para.args = this;
121 para.name = name;
122 para.priority = priority;
123
124 bool res = CreatePThread(para, stack, &thread_);
125 if (!res) {
126 status_ = ThreadStatus::UNKNOWN_ERROR; // something happened!
127 running_ = false;
128 thread_ = INVALID_PTHREAD_T;
129 return ThreadStatus::UNKNOWN_ERROR;
130 }
131
132 return ThreadStatus::OK;
133 }
134
Join()135 ThreadStatus Thread::Join()
136 {
137 // If the two thread IDs are equal, pthread_equal() returns a non-zero value; otherwise, it returns 0.
138 if (pthread_equal(thread_, pthread_self()) != 0) {
139 return ThreadStatus::WOULD_BLOCK;
140 }
141
142 std::unique_lock<std::mutex> lk(lock_);
143 while (running_) {
144 cvThreadExited_.wait(lk);
145 }
146
147 return status_;
148 }
149
NotifyExitSync()150 ThreadStatus Thread::NotifyExitSync()
151 {
152 // If the two thread IDs are equal, pthread_equal() returns a non-zero value; otherwise, it returns 0.
153 if (pthread_equal(thread_, pthread_self()) != 0) {
154 // don't call NotifyExitSync() from this !;
155 return ThreadStatus::WOULD_BLOCK;
156 }
157
158 std::unique_lock<std::mutex> lk(lock_);
159 exitPending_ = true;
160
161 while (running_ == true) {
162 cvThreadExited_.wait(lk);
163 }
164
165 exitPending_ = false;
166
167 return status_;
168 }
169
NotifyExitAsync()170 void Thread::NotifyExitAsync()
171 {
172 std::lock_guard<std::mutex> lk(lock_);
173 exitPending_ = true;
174 }
175
ReadyToWork()176 bool Thread::ReadyToWork()
177 {
178 return true;
179 }
180
IsExitPending() const181 bool Thread::IsExitPending() const
182 {
183 std::lock_guard<std::mutex> lk(lock_);
184 return exitPending_;
185 }
186
IsRunning() const187 bool Thread::IsRunning() const
188 {
189 std::lock_guard<std::mutex> lk(lock_);
190 return running_;
191 }
192
ThreadStart(void * args)193 int Thread::ThreadStart(void* args)
194 {
195 Thread* const self = static_cast<Thread*>(args);
196 bool first = true;
197
198 do {
199 bool result = false;
200 if (first) {
201 first = false;
202 if (self->ReadyToWork() && !self->IsExitPending()) {
203 result = self->Run();
204 }
205 } else {
206 result = self->Run();
207 }
208
209 {
210 std::unique_lock<std::mutex> lk(self->lock_);
211 if ((!result) || self->exitPending_) {
212 self->exitPending_ = true;
213 self->running_ = false;
214 self->thread_ = INVALID_PTHREAD_T;
215 self->cvThreadExited_.notify_all();
216 break;
217 }
218 }
219 } while (true);
220
221 return 0;
222 }
223
224 } // namespace OHOS