This repository has been archived by the owner on Dec 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.inc
49 lines (39 loc) · 1.24 KB
/
thread.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright (c) 2018 Formula Slug. All Rights Reserved.
#pragma once
#include <stdint.h>
#include <functional>
#include <memory>
#include <utility>
#include "hal.h"
template <typename Callable>
struct State {
explicit State(Callable&& f) : func(std::forward<Callable>(f)) {}
Callable func;
};
/**
* Create and launch a thread.
*
* @param function The address of the function to run as the new task.
* @param args A parameter pack of arguments to pass to the function.
*/
template <class Function, class... Args>
thread::thread(tprio_t priority, Function&& func, Args&&... args) {
auto funcWrapper =
std::bind(std::forward<Function>(func), std::forward<Args>(args)...);
auto state =
std::make_unique<State<decltype(funcWrapper)>>(std::move(funcWrapper));
const auto threadFunc = [](void* arg) {
auto state = reinterpret_cast<State<decltype(funcWrapper)>*>(arg);
state->func();
delete state;
};
m_thread = chThdCreateStatic(m_workingArea,
sizeof(m_workingArea), // Stack size
priority, threadFunc, state.get());
if (m_thread == nullptr) {
chSysHalt("Out of memory");
}
// thread has taken control of memory
state.release();
m_joinable = true;
}