7 years, 8 months ago.

How to use RTOS Thread::start() in mbed OS 5?

Having the RTOS integrated into the new mbed OS 5 is great. But, there are minimal usage examples at this time. I would like to use the member function Thread::start(). Specifically, I want to use the form that allows specifying the task object argument (pointer) and method as parameters.

See https://docs.mbed.com/docs/mbed-os-api/en/mbed-os-5.1.0/api/classrtos_1_1Thread.html#a72d794748cd184690c4f10741541c0e3.

This is defined as a function template in the Thread class. How do I instantiate this in my code? I would like to be able to pass a "task" object to the "task" method as an argument. The old RTOS supported that, but it is now labeled as MBED_DEPRECATED. I would like to start porting my code to the new RTOS in mbed OS 5. Any help would be appreciated.

1 Answer

7 years, 8 months ago.

Hello,

The old constructor is still usable but is now deprecated because it doesn't allow user code to catch errors. Now instantiation and start of a thread are decoupled. As an interesting side effect this change also allow user code to declare threads globally or as class members without worries about when the thread start.

To start a thread it is quite easy:

struct Foo { 
   // member function executed in a thread
   void some_work();
};

// free function to execute in a thread
void some_work();


int main() { 
   Thread member_function_thread;   
   Thread free_function_thread;

   Foo foo;

   // start a thread from a member function
   osStatus err = member_function_thread.start(&foo, &Foo::some_work);
   if (err) { 
      // treat error here if any
   }

   // start a thread from a free function
   osStatus err = free_function_thread.start(&some_work);
   if (err) { 
      // treat error here if any
   }

   // wait for threads termination
   member_function_thread.join();  
   free_function_thread.join(); 
}

Somehow the generated documentation is not complete and does not show the overloads of Thread::start. You can see them here.

Accepted Answer

Vincent,

Thank you. That will do want I need to to.

posted by David G 15 Aug 2016

link to documentation on Vincent's post broken return a 404 page not found error

posted by Steve Mylroie 04 Nov 2016

@steve, the file has moved in another place with mbed OS 5.2: you can get it here: https://github.com/ARMmbed/mbed-os/blob/master/rtos/Thread.h#L197-L216

posted by Vincent (pan-) Coubard 07 Nov 2016

How many threads can you use in total?

posted by Rishabh Gupta 22 Mar 2018

start without a callback now is deprecated it is recommended to use callback:

threadInstance.start(callback(&ObjectInstance,&Object::ObjectFunction));

for example: threadBlinker.start(callback(&StatBlink,&StatusBlinker::blink));

Where threadBlinker is an object of Thread class StatBlink is an instance of StatusBlinker class blink is a method of StatusBlinker

posted by Vladislav Kravchenko 30 Sep 2019