首页 > 解决方案 > 是否有获取当前线程的 STL 方式?

问题描述

我目前正在从一个大型应用程序中分解 GLib 函数。

在某些函数中,它使用g_thread_self()返回指向当前线程的指针的 GLib 函数。

我知道在 STL 中有一个std::this_thread::get_id()函数,但是因为我有一个成员变量来保存指向线程的指针,所以我希望能够直接保存线程的地址。

这在 C++17 中可行吗?

假设我有一个 MyThread 类(请注明我没有编写此源代码的逻辑):

class MyThread {
public: 
    void startRoutine(MyThread* other)
    {
        // ...
        other->loop();

        // ...
        // here, I need to know if my thread is joinable
        if (other->_thread && other->_thread->joinable()) {
            other->thread = nullptr;
        }
    }
    bool isInsideCurrentThread() 
    {
        // `this_thread()` is the function I'm looking for
        return nullptr == _thread || this_thread() == _thread;
    };
    // ...

private:
    std::thread* _thread;
}

标签: c++multithreadingstl

解决方案


No, as of C++17 (or 20) there is no standard way to obtain a pointer to a std::thread instance managing the current thread.


推荐阅读