Skip to content

Commit

Permalink
cpp: thread: support for std::thread and std::this_thread
Browse files Browse the repository at this point in the history
This commit adds support for std::thread and std::this_thread
when the configured C++ standard is >= C++11.

The implementation uses POSIX threads under the hood.

Fixes zephyrproject-rtos#25569

Signed-off-by: Christopher Friedt <[email protected]>
  • Loading branch information
cfriedt committed Aug 30, 2023
1 parent f0c10d0 commit 28a5050
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0

add_subdirectory(abi)

add_subdirectory(std)
add_subdirectory_ifdef(CONFIG_MINIMAL_LIBCPP minimal)
8 changes: 8 additions & 0 deletions lib/cpp/Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ config CPP_RTTI

endif # !MINIMAL_LIBCPP

config CPP_STD_THREAD
bool "Support for std::thread"
default y if !STD_CPP98
depends on !STD_CPP98
select POSIX_API
help
This option enables support for std::thread and std::this_thread.

config CPP_STATIC_INIT_GNU
# As of today only ARC MWDT toolchain doesn't support GNU-compatible
# initialization of CPP static objects, new toolchains can be added
Expand Down
1 change: 1 addition & 0 deletions lib/cpp/std/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
zephyr_sources_ifdef(CONFIG_CPP_STD_THREAD cpp_std_thread.cpp)
74 changes: 74 additions & 0 deletions lib/cpp/std/cpp_std_thread.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2020 Friedt Professional Engineering Services, Inc
*
* SPDX-License-Identifier: Apache-2.0
*/

#include <zephyr/kernel.h>

#include <system_error>
#include <thread>

namespace std
{
void thread::detach()
{
int err;
thread::id tid;
::pthread_t pth;

tid = this->get_id();
pth = (::pthread_t)tid._M_thread;

err = ::pthread_detach(pth);
if (err) {
__throw_system_error(err);
}
}

void thread::join()
{
int err;
thread::id tid;
::pthread_t pth;
void *unused;

tid = this->get_id();
pth = (::pthread_t)tid._M_thread;

err = ::pthread_join(pth, &unused);
if (err) {
__throw_system_error(err);
}
}

thread::_State::~_State()
{
}

unsigned int thread::hardware_concurrency() noexcept
{
return CONFIG_MP_NUM_CPUS;
}

extern "C" {
static void *execute_native_thread_routine(void *__p)
{
thread::_State_ptr __t{static_cast<thread::_State *>(__p)};
__t->_M_run();
return nullptr;
}
}

void thread::_M_start_thread(_State_ptr state, void (*)())
{
const int err =
__gthread_create(&_M_id._M_thread, &execute_native_thread_routine, state.get());

if (err) {
__throw_system_error(err);
}
state.release();
}

} /* namespace std */

0 comments on commit 28a5050

Please sign in to comment.