1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #include "pw_thread/thread.h"
15
16 #include "pw_assert/check.h"
17 #include "pw_thread_embos/config.h"
18 #include "pw_thread_embos/context.h"
19 #include "pw_thread_embos/options.h"
20
21 using pw::thread::embos::Context;
22
23 namespace pw::thread {
24
ThreadEntryPoint(void * void_context_ptr)25 void Context::ThreadEntryPoint(void* void_context_ptr) {
26 Context& context = *reinterpret_cast<Context*>(void_context_ptr);
27
28 // Invoke the user's thread function. This may never return.
29 context.fn_();
30 context.fn_ = nullptr;
31
32 // Use a task only critical section to guard against join() and detach().
33 OS_SuspendAllTasks();
34 if (context.detached()) {
35 // There is no threadsafe way to re-use detached threads. Callbacks
36 // registered through OS_AddOnTerminateHook CANNOT be used for this as they
37 // are invoked before the kernel is done using the task's TCB!
38 // However to enable unit test coverage we go ahead and clear this.
39 context.set_in_use(false);
40
41 #if PW_THREAD_JOINING_ENABLED
42 // If the thread handle was detached before the thread finished execution,
43 // i.e. got here, then we are responsible for cleaning up the join event
44 // object.
45 OS_EVENT_Delete(&context.join_event_object());
46 #endif // PW_THREAD_JOINING_ENABLED
47
48 // Re-enable the scheduler before we delete this execution. Note this name
49 // is a bit misleading as reference counting is used.
50 OS_ResumeAllSuspendedTasks();
51 OS_TerminateTask(nullptr);
52 PW_UNREACHABLE;
53 }
54
55 // Otherwise the task finished before the thread was detached or joined, defer
56 // cleanup to Thread's join() or detach().
57 context.set_thread_done();
58 OS_ResumeAllSuspendedTasks();
59
60 #if PW_THREAD_JOINING_ENABLED
61 OS_EVENT_Set(&context.join_event_object());
62 #endif // PW_THREAD_JOINING_ENABLED
63
64 // Let the thread handle owner terminate this task when they detach or join.
65 OS_Suspend(nullptr);
66 PW_UNREACHABLE;
67 }
68
TerminateThread(Context & context)69 void Context::TerminateThread(Context& context) {
70 // Stop the other task first.
71 OS_TerminateTask(&context.tcb());
72
73 // Mark the context as unused for potential later re-use.
74 context.set_in_use(false);
75
76 #if PW_THREAD_JOINING_ENABLED
77 // Just in case someone abused our API, ensure their use of the event group is
78 // properly handled by the kernel regardless.
79 OS_EVENT_Delete(&context.join_event_object());
80 #endif // PW_THREAD_JOINING_ENABLED
81 }
82
CreateThread(const embos::Options & options,Function<void ()> && thread_fn)83 void Context::CreateThread(const embos::Options& options,
84 Function<void()>&& thread_fn) {
85 // Can't use a context more than once.
86 PW_DCHECK(!in_use());
87
88 // Reset the state of the static context in case it was re-used.
89 set_in_use(true);
90 set_detached(false);
91 set_thread_done(false);
92 #if PW_THREAD_JOINING_ENABLED
93 OS_EVENT_CreateEx(&join_event_object(), OS_EVENT_RESET_MODE_AUTO);
94 #endif // PW_THREAD_JOINING_ENABLED
95
96 // Copy over the thread name.
97 set_name(options.name());
98
99 // In order to support functions which return and joining, a delegate is
100 // deep copied into the context with a small wrapping function to actually
101 // invoke the task with its arg.
102 set_thread_routine(std::move(thread_fn));
103
104 OS_CreateTaskEx(&tcb(),
105 name(),
106 options.priority(),
107 Context::ThreadEntryPoint,
108 stack().data(),
109 static_cast<OS_UINT>(stack().size_bytes()),
110 options.time_slice_interval(),
111 this);
112 }
113
Thread(const thread::Options & facade_options,Function<void ()> && entry)114 Thread::Thread(const thread::Options& facade_options, Function<void()>&& entry)
115 : native_type_(nullptr) {
116 // Cast the generic facade options to the backend specific option of which
117 // only one type can exist at compile time.
118 auto options = static_cast<const embos::Options&>(facade_options);
119 PW_DCHECK_NOTNULL(options.context(), "The Context is not optional");
120 native_type_ = options.context();
121 native_type_->CreateThread(options, std::move(entry));
122 }
123
detach()124 void Thread::detach() {
125 PW_CHECK(joinable());
126
127 OS_Suspend(&native_type_->tcb());
128 native_type_->set_detached();
129 const bool thread_done = native_type_->thread_done();
130 OS_Resume(&native_type_->tcb());
131
132 if (thread_done) {
133 // The task finished (hit end of Context::ThreadEntryPoint) before we
134 // invoked detach, clean up the thread.
135 Context::TerminateThread(*native_type_);
136 } else {
137 // We're detaching before the task finished, defer cleanup to the task at
138 // the end of Context::ThreadEntryPoint.
139 }
140
141 // Update to no longer represent a thread of execution.
142 native_type_ = nullptr;
143 }
144
145 #if PW_THREAD_JOINING_ENABLED
join()146 void Thread::join() {
147 PW_CHECK(joinable());
148 PW_CHECK(this_thread::get_id() != get_id());
149
150 OS_EVENT_Wait(&native_type_->join_event_object());
151
152 // No need for a critical section here as the thread at this point is
153 // waiting to be deleted.
154 Context::TerminateThread(*native_type_);
155
156 // Update to no longer represent a thread of execution.
157 native_type_ = nullptr;
158 }
159 #endif // PW_THREAD_JOINING_ENABLED
160
161 } // namespace pw::thread
162