From ee8a33c5685a915d9c8650191138f39d01eee994 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Thu, 20 Jun 2019 19:51:09 -0700 Subject: [PATCH] wpiutil: SafeThread: Add thread id, support getting shared_ptr (#1722) Rename base class function from GetThread to GetThreadSharedPtr. --- wpiutil/src/main/native/cpp/SafeThread.cpp | 6 ++++-- wpiutil/src/main/native/include/wpi/SafeThread.h | 10 ++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/wpiutil/src/main/native/cpp/SafeThread.cpp b/wpiutil/src/main/native/cpp/SafeThread.cpp index 52ac70077e..1d0fc0f41a 100644 --- a/wpiutil/src/main/native/cpp/SafeThread.cpp +++ b/wpiutil/src/main/native/cpp/SafeThread.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) 2015-2018 FIRST. All Rights Reserved. */ +/* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -32,6 +32,7 @@ void detail::SafeThreadOwnerBase::Start(std::shared_ptr thr) { std::lock_guard lock(m_mutex); if (auto thr = m_thread.lock()) return; m_stdThread = std::thread([=] { thr->Main(); }); + thr->m_threadId = m_stdThread.get_id(); m_thread = thr; } @@ -80,7 +81,8 @@ detail::SafeThreadOwnerBase::GetNativeThreadHandle() { return m_stdThread.native_handle(); } -std::shared_ptr detail::SafeThreadOwnerBase::GetThread() const { +std::shared_ptr detail::SafeThreadOwnerBase::GetThreadSharedPtr() + const { std::lock_guard lock(m_mutex); return m_thread.lock(); } diff --git a/wpiutil/src/main/native/include/wpi/SafeThread.h b/wpiutil/src/main/native/include/wpi/SafeThread.h index a2de41426e..d4b48f7b14 100644 --- a/wpiutil/src/main/native/include/wpi/SafeThread.h +++ b/wpiutil/src/main/native/include/wpi/SafeThread.h @@ -27,6 +27,7 @@ class SafeThread { mutable wpi::mutex m_mutex; std::atomic_bool m_active{true}; wpi::condition_variable m_cond; + std::thread::id m_threadId; }; namespace detail { @@ -83,7 +84,7 @@ class SafeThreadOwnerBase { protected: void Start(std::shared_ptr thr); - std::shared_ptr GetThread() const; + std::shared_ptr GetThreadSharedPtr() const; private: mutable wpi::mutex m_mutex; @@ -107,7 +108,12 @@ class SafeThreadOwner : public detail::SafeThreadOwnerBase { using Proxy = typename detail::SafeThreadProxy; Proxy GetThread() const { - return Proxy(detail::SafeThreadOwnerBase::GetThread()); + return Proxy(detail::SafeThreadOwnerBase::GetThreadSharedPtr()); + } + + std::shared_ptr GetThreadSharedPtr() const { + return std::static_pointer_cast( + detail::SafeThreadOwnerBase::GetThreadSharedPtr()); } };