【发布时间】: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