C++ threads std::thread in ESP-IDF is implemented on top of ESP-pthread component
The C++ threads created using the standard thread class constructor actually use the under the hood ESP-pthread. On the other hand ESP-pthread is actually using FreeRtos Task
Now we will go through this example of esp-idf Example to use pthread in esp32 https://github.com/espressif/esp-idf/tree/master/examples/system/cpp_pthread
The example is written in C++
The esp pthread configuration structure looks like
To create a std::thread type thread a esp_pthread configuration is needed
auto keyword in C++
The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer . it is available from C++ 11
Here I am explaining the code by going through the debug messages after running the program.
The example first creates a thread that can run at any core
std::thread any_core(thread_func_any_core);
Then it creates a thread to be run on core 0 . this thread’s inherit_cfg is set to true .
std::thread thread_1(spawn_another_thread);
this thread in turn creates another thread which inherits the same configuration of the thread which created it
std::thread inherits(thread_func_inherited);
Then a thread is created to be run on core 1 only
std::thread thread_2(thread_func);
The main() of the app has an infinite loop that prints some information. This infinite loop itself is a thread too
All the threads sleeps for 5 second
The example uses stringstream type object to construct debug messages. the constructed message is printed via the ESP_LOGI() function
Summary
The C++ std::thread is a popular way to design multithreaded applications. Application developers are more familiar with this API than FreeRTOS API . So it’s a great decision by espressif to port std::thread for ESP32 . Application developers can port C++ std::thread based applications to ESP32 architecture easily. Also if you want to design a C++ based application with thread functionality this is a good design pattern
This article give me various amount of knowledge of embedded system thank you for posting such knowledgeable post
ReplyDeleteJTAG