xref: /nrf52832-nimble/rt-thread/components/cplusplus/Thread.cpp (revision 167494296f0543431a51b6b1b83e957045294e05)
1 /*
2  * Copyright (c) 2006-2018, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  */
9 #include "Thread.h"
10 
11 using namespace rtthread;
12 
13 Thread::Thread(rt_uint32_t stack_size,
14                rt_uint8_t  priority,
15                rt_uint32_t tick,
16                const char *name)
17 : _entry(RT_NULL), _param(RT_NULL), started(false)
18 {
19     rt_event_init(&_event, name, 0);
20 
21     _thread = rt_thread_create(name,
22                                (thread_func_t)func,
23                                this,
24                                stack_size,
25                                priority,
26                                tick);
27 }
28 
29 Thread::Thread(void (*entry)(void *p),
30                void *p,
31                rt_uint32_t stack_size,
32                rt_uint8_t  priority,
33                rt_uint32_t tick,
34                const char *name)
35 : _entry(RT_NULL), _param(p), started(false)
36 {
37     rt_event_init(&_event, name, 0);
38 
39     _thread = rt_thread_create(name,
40                                (thread_func_t)func,
41                                this,
42                                stack_size,
43                                priority,
44                                tick);
45 }
46 
47 Thread::~Thread()
48 {
49     rt_thread_delete(_thread);
50 }
51 
52 bool Thread::start()
53 {
54     if (rt_thread_startup(_thread) == RT_EOK)
55     {
56         started = true;
57     }
58 
59     return started;
60 }
61 
62 void Thread::sleep(int32_t millisec)
63 {
64     rt_int32_t tick;
65 
66     if (millisec < 0)
67         tick = 1;
68     else
69         tick = rt_tick_from_millisecond(millisec);
70 
71     rt_thread_delay(tick);
72 }
73 
74 void Thread::func(Thread *pThis)
75 {
76     if (pThis->_entry != RT_NULL)
77     {
78         pThis->_entry(pThis->_param);
79     }
80     else
81     {
82         pThis->run();
83     }
84 
85     rt_event_send(&pThis->_event, 1);
86 }
87 
88 void Thread::run()
89 {
90     /* please overload this method */
91 }
92 
93 void Thread::wait(int32_t millisec)
94 {
95     join(millisec);
96 }
97 
98 void Thread::join(int32_t millisec)
99 {
100     if (started)
101     {
102         rt_int32_t tick;
103 
104         if (millisec < 0)
105             tick = -1;
106         else
107             tick = rt_tick_from_millisecond(millisec);
108 
109         rt_event_recv(&_event, 1, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, tick, RT_NULL);
110     }
111 }
112