【问题标题】:Is there an STL way for getting the current thread?是否有获取当前线程的 STL 方式?
【发布时间】:2021-09-19 18:31:39
【问题描述】:

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

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

我知道在 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;
}

【问题讨论】:

  • “线程地址”是什么意思?实际线程由操作系统管理,id 可能是您可以获得的最好的地址。如果你能从当前线程中获得一个std::thread,那就太糟糕了,因为这样就可能有两个std::thread 管理同一个线程。
  • xy problem?如果你能得到一个地址,你会用这个地址做什么?也许有不同的方法来解决你的实际问题
  • 我明白你的意思。显然,我正在使用的课程不断地进行所有者和调用者检查,这可以仅使用 id 来解决,但它也会检查线程是否可连接,这是我无法仅使用 id 实现的给定的。
  • g_thread_self() 返回一个指向 GLib 结构的指针,该结构包含线程 ID 的副本。 GLib 结构不是“线程的地址”,它只是 GLib 结构的地址。 std::thread 可用于查看线程是否可连接。
  • 不确定我是否理解,从线程中你知道它是可连接的,除非它是分离的。

标签: c++ multithreading stl


【解决方案1】:

不,从 C++17(或 20)开始,没有标准方法可以获取指向管理当前线程的 std::thread 实例的指针。

【讨论】:

    【解决方案2】:

    不,没有标准函数可以返回指向引用当前线程的std::thread 包装器的指针。

    您可以使用关联容器将本机 id 映射到 std::thread 对象,但这不是实现示例函数所必需的。你可以这样实现它:

    bool isInsideCurrentThread() 
    {
        return std::this_thread::get_id() == _thread->get_id();
    };
    

    【讨论】:

    • 谢谢,我知道了。但是,我仍然需要不同线程的可连接能力,另一方面,能够将某个线程的地址保存在同一个变量中。
    • @taiBsu I would still need a different thread's ability to be joinable 这就是std::thread::joinable 的用途。
    猜你喜欢
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多