Threading
Thread class - Threading
Thread constructor os_thread_fn_t - Threading
// PROTOTYPE
Thread(const char* name,
os_thread_fn_t function,
void* function_param=NULL,
os_thread_prio_t priority=OS_THREAD_PRIORITY_DEFAULT,
size_t stack_size=OS_THREAD_STACK_SIZE_DEFAULT)
// os_thread_fn_t
typedef os_thread_return_t (*os_thread_fn_t)(void* param);
typedef void os_thread_return_t;
// Thread function prototype
void myThreadFunction(void *param)
name
a short string that can be used to identify your thread as a c-string of up to 16 ASCII characters.function
The function that will be run in the new thread.function_param
A parameter passed to the new thread. Often this is used for a class instance pointer (this
).priority
The thread priority, typicallyOS_THREAD_PRIORITY_DEFAULT
. See os_thread_prio_t, above, for other values.stack_size
The stack size in bytes, typicallyOS_THREAD_STACK_SIZE_DEFAULT
(3 Kbytes). See Thread stack size, above, for more information.
Thread constructor wiring_thread_fn_t - Threading
// PROTOTYPE
Thread(const char *name,
wiring_thread_fn_t function,
os_thread_prio_t priority=OS_THREAD_PRIORITY_DEFAULT,
size_t stack_size=OS_THREAD_STACK_SIZE_DEFAULT)
// wiring_thread_fn_t
typedef std::function<os_thread_return_t(void)> wiring_thread_fn_t;
typedef void os_thread_return_t;
// Thread function prototype
void myThreadFunction()
name
a short string that can be used to identify your thread as a c-string of up to 16 ASCII characters.function
The function that will be run in the new thread.priority
The thread priority, typicallyOS_THREAD_PRIORITY_DEFAULT
. See os_thread_prio_t, above, for other values.stack_size
The stack size in bytes, typicallyOS_THREAD_STACK_SIZE_DEFAULT
(3 Kbytes). See Thread stack size, above, for more information.
The function
parameter is a std::function
which means it can be a C++11 lambda, which makes it easy to make the thread function a class member. For example:
class MyClass7 {
public:
MyClass7();
virtual ~MyClass7();
void start(os_thread_prio_t priority=OS_THREAD_PRIORITY_DEFAULT, size_t stack_size=OS_THREAD_STACK_SIZE_DEFAULT);
protected:
void threadFunction();
// This class cannot be copied
MyClass7(const MyClass7&) = delete;
MyClass7& operator=(const MyClass7&) = delete;
Thread *thread = nullptr;
int counter = 0;
};
MyClass7::MyClass7() {
}
MyClass7::~MyClass7() {
delete thread;
}
void MyClass7::start(os_thread_prio_t priority, size_t stack_size) {
thread = new Thread("MyClass7", [this]() { threadFunction(); }, priority, stack_size);
}
void MyClass7::threadFunction() {
while(true) {
Log.info("MyClass7::threadFunction counter=%d", ++counter);
delay(10000);
}
}
Calling the code:
MyClass7 *myClass7 = new MyClass7();
myClass7->start();
See callback functions for more information.