gpt4 book ai didi

c++ - 在运行之前获取 std::thread 的 thread:id?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:40 30 4
gpt4 key购买 nike

我正在尝试在 C++ 11 的 std::thread 之上构建一个线程安全层,其中每个对象都被分配给一个拥有的线程,并且某些调用在它们执行时可能会引发硬错误在错误的线程上使用。拥有线程是唯一可以将对象传输到另一个线程的线程。

我已经全部正常工作了,除了我找不到在线程实际运行之前获取线程的 thread::id 的方法。我需要在传递之前将新线程的 ID 附加到该对象。

如果我用

std::thread newThread( [theObject]()
{
// use theObject here.
} );

我最早可以获得线程 ID 的时间是在线程对象定义之后,此时线程已经在运行。

我看到 std::thread 有一个默认的构造函数,但我看不出有什么方法可以给它一个函数,让它在之后的线程上运行。

有没有办法在线程上执行两步构建,或者在创建时控制线程的 ID?

最佳答案

与其在线程开始运行之前获取线程的 ID,不如考虑让线程执行的函数在启动前进行一些初始设置。例如,您可以这样做:

bool isReady = false;
bool wasReceived = false;
std::mutex mutex;
std::condition_variable condition;

std::thread newThread([theObject, &isReady, &mutex, &condition] {
/* Wait until we've been cleared to go. */
std::unique_lock<std::mutex> lock(isReady);
condition.wait(lock, [&isReady] { return isReady; });

/* Signal that we're done. */
wasReceived = true;
lock.unlock();
condition.notify_one();

/* Put code here to do whatever it is that the thread should do. */
});

/* Read the thread's ID. It's currently waiting for us. */
auto id = newThread.get_id();

/* Tell the thread that we're ready for it. */
std::unique_lock<std::mutex> lock(mutex);
isReady = true;
condition.notify_one();

/* Wait until the thread has confirmed that it's ready. */
condition.wait(lock, [&] { return wasReceived; });

这将创建线程并让它等待,直到创建者有机会读取其 ID。一旦发生这种情况,创建者就会等待线程确认它已准备就绪,然后您可以根据需要使用线程 ID。

当心上面代码中的错误——它完全未经测试。 :-)

关于c++ - 在运行之前获取 std::thread 的 thread:id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51794793/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com