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 #ifndef AIE_THREAD_UNIX_H
17 #define AIE_THREAD_UNIX_H
18 
19 #include <chrono>
20 #include <pthread.h>
21 
22 #include "protocol/retcode_inner/aie_retcode_inner.h"
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
28 #define THREAD_SCOPE_PROCESS 0x1
29 #define THREAD_SCOPE_SYSTEM 0x2
30 #define THREAD_DEFAULT_STACK_SIZE 0
31 
32 typedef struct {
33     size_t stackSize;
34     int scope;
35 } PthreadAttr;
36 
37 const size_t THREAD_DATA_LEN = 32;
38 typedef struct {
39     char data[THREAD_DATA_LEN];
40 } PthreadData;
41 
42 typedef void *(*PthreadRoutine)(void *);
43 
44 /**
45  * initialize PthreadAttr
46  *
47  * @param [in,out]  attr
48  */
49 void InitThreadAttr(PthreadAttr &attr);
50 
51 /**
52  * set thread stack size
53  *
54  * @param [in] attr *PthreadAttr
55  * @param [in] size
56  */
57 void SetThreadAttrStackSize(PthreadAttr &attr, size_t size);
58 
59 /**
60  * set thread scope
61  *
62  * @param [in] attr *PthreadAttr
63  * @param [in] scope THREAD_SCOPE_PROCESS or THREAD_SCOPE_SYSTEM
64  */
65 void SetThreadAttrScope(PthreadAttr &attr, int scope);
66 
67 /**
68  * Init thread
69  *
70  * @param [in,out] tr PthreadData
71  * @return RETCODE_SUCCESS: init thread success, RETCODE_FAILURE: init thread failed.
72  */
73 int InitThread(PthreadData &tr);
74 
75 /**
76  * create thread
77  *
78  * @param [out] tr PthreadData
79  * @param [in] attr thread attribute
80  * @param [in] func thread function
81  * @param [in] param thread function params
82  * @return RETCODE_SUCCESS: create success, RETCODE_FAILURE: create failed. error information
83  */
84 int CreateOneThread(PthreadData &tr, PthreadAttr *attr, PthreadRoutine func, void *param);
85 
86 /**
87  * get thread id from pec_thread_t
88  *
89  * @param [in] tr thread info
90  * @return return id
91  */
92 unsigned long GetThreadIdUnix(const PthreadData &tr);
93 
94 /**
95  * judge if thread is running
96  *
97  * @param [in] tid thread ID
98  * @return true is existed, false is not existed
99  */
100 bool IsThreadRunning(unsigned long tid);
101 
102 /**
103  * wait for thread end
104  *
105  * @param [in] tr thread info
106  * @return RETCODE_SUCCESS
107  */
108 int WaitThread(PthreadData &tr);
109 
110 #ifdef __cplusplus
111 }
112 #endif
113 
114 #endif // AIE_THREAD_UNIX_H
115