Mistake on this page?
Report an issue in GitHub or email us

ThisThread

Use the ThisThread class to control the current thread.

Unlike the Thread API, which allows you to create, join and end threads, ThisThread lets you control the thread that's currently running. A thread may not have a corresponding Mbed Thread object because you can create a thread directly with CMSIS-RTOS APIs, or it might be main's thread. You can't manipulate those with Thread methods, but ThisThread functions still work from inside them.

ThisThread class reference

ThisThread example

Spawn a thread to blink for 5 seconds before setting a flag to trigger the thread to terminate.

#include "mbed.h"
#include "rtos.h"

#define STOP_FLAG 1

// Toggles LED
void blink(DigitalOut *led)
{
    // Toggle the LED every second, until the STOP_FLAG is set
    while (!ThisThread::flags_wait_any_for(STOP_FLAG, 1s)) {
        *led = !*led;
    }
}

// Creates a thread to toggle an LED for 5 seconds
int main()
{
    Thread thread;
    DigitalOut led1(LED1);
    thread.start(callback(blink, &led1));
    // Pause the main thread for 5 seconds
    ThisThread::sleep_for(5s);
    // Set the flag checked by the thread to stop the loop
    thread.flags_set(STOP_FLAG);
    // Wait for the thread to terminate
    thread.join();
}

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.