Let me start by mentioning that I'm aware that my solution is neither thread safe nor clean at all... but that's why I'm writing this question:
I'm trying to implement a thread in a C++ class in Zephyr that can access a member variable. However, this is more of a general C++ question.
Here's my working solution:
- stepper.h
class Stepper
{
...
private:
double speed;
struct k_thread stepper_thread;
/* Stepper thread entry */
static void stepper_thread_entry(void *, void *, void *);
/* Stepper thread function */
void stepper_thread_function(auto& desired_speed);
};
- stepper.cpp
Stepper::Stepper(void) : speed(0)
{
k_tid_t stepper_thread_tid = k_thread_create(&stepper_thread,
stepper_thread_stack_area,
K_THREAD_STACK_SIZEOF(stepper_thread_stack_area),
Stepper::stepper_thread_entry,
this, NULL, NULL,
STEPPER_THREAD_PRIORITY, 0, K_MSEC(10));
}
...
void Stepper::stepper_thread_entry(void *instance, void *, void *)
{
auto thead_instance = reinterpret_cast<Stepper *>(instance);
thead_instance->stepper_thread_function(thead_instance->speed);
}
void Stepper::stepper_thread_function(double& desired_speed)
{
// access desired_speed
...
}
I'm not especially happy with the implementation in Stepper::stepper_thread_entry, but it was the only way i found to work around the fact that the K_THREAD_STACK_SIZEOF macro requires a static function.
Is there a cleaner way to implement this?
Thanks in advance :)
edit: fixed formatting erros