Search code examples
c++stm32mbed

How to pass multiple arguments to spawned threads (Mbed)?


I use Mbed RTOS and I need to pass multiple arguments to the threaded function.

There is an example in API docs:

#include "mbed.h"

Thread thread;
DigitalOut led1(LED1);
volatile bool running = true;

// Blink function toggles the led in a long running loop
void blink(DigitalOut *led) {
    while (running) {
        *led = !*led;
        wait(1);
    }
}

// Spawns a thread to run blink for 5 seconds
int main() {
    thread.start(callback(blink, &led1));
    wait(5);
    running = false;
    thread.join();
}

But there is only one argument to pass.

Is there a convenient way to pass multiple arguments? I don't like the idea to put them into a struct and pass the struct. But I can't see any other way to do it.


Solution

  • You could use an std::tuple<> instead of defining a new struct. This is simpler in most cases, although as the number of argument members goes up, you might find yourself wanting a struct after all, to get names for them instead of having to std::get() by type or index.

    There is unlikely to be any other way, as such callback systems typically only offer a single 'user data' pointer, and my brief googling about Mbed suggest it is the same.