1 /*
2 * Copyright (c) 2020-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 #ifndef GRAPHIC_LITE_THREAD_H
17 #define GRAPHIC_LITE_THREAD_H
18
19 #include <stdint.h>
20 #ifdef _WIN32
21 #include <windows.h>
22 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
23 #include <pthread.h>
24 #endif // WIN32
25
26 typedef void* ThreadId;
27 #ifdef _WIN32
28 typedef DWORD(WINAPI* Runnable)(LPVOID lpThreadParameter);
29 #else
30 typedef void* (*Runnable)(void* argv);
31 #endif
32 typedef struct ThreadAttr ThreadAttr;
33 struct ThreadAttr {
34 const char* name; // name of the thread
35 uint32_t stackSize; // size of stack
36 uint8_t priority; // initial thread priority
37 uint8_t reserved1; // reserved1 (must be 0)
38 uint16_t reserved2; // reserved2 (must be 0)
39 };
40
ThreadCreate(Runnable entry,void * arg,const ThreadAttr * attr)41 static inline ThreadId ThreadCreate(Runnable entry, void* arg, const ThreadAttr* attr)
42 {
43 #ifdef _WIN32
44 HANDLE handle = CreateThread(NULL, 0, entry, arg, 0, NULL);
45 return (ThreadId)handle;
46 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
47 pthread_attr_t threadAttr;
48 pthread_attr_init(&threadAttr);
49 pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
50 if (attr != NULL) {
51 pthread_attr_setstacksize(&threadAttr, attr->stackSize);
52 struct sched_param sched = {attr->priority};
53 pthread_attr_setschedparam(&threadAttr, &sched);
54 }
55 pthread_t threadId;
56 int ret = pthread_create(&threadId, &threadAttr, entry, arg);
57 if (ret != 0) {
58 return NULL;
59 }
60 return (ThreadId)threadId;
61 #else
62 return NULL;
63 #endif
64 }
ThreadYield(void)65 static inline void ThreadYield(void)
66 {
67 #ifdef _WIN32
68 SwitchToThread();
69 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__
70 sched_yield();
71 #endif
72 }
73 #endif // GRAPHIC_LITE_THREAD_H
74