gpt4 book ai didi

c++ - 从 usleep 中唤醒一个 std::thread

转载 作者:可可西里 更新时间:2023-11-01 17:36:50 27 4
gpt4 key购买 nike

考虑以下示例:

#include <iostream>
#include <fstream>
#include <unistd.h>

#include <signal.h>
#include <thread>

void sleepy() {
usleep(1.0E15);
}

int main() {
std :: thread sleepy_thread(sleepy);

// Wake it up somehow...?

sleepy_thread.join();
}

这里我们有一个永远休眠的线程。我想加入它,而不必永远等待它自发地从 sleep 中醒来。有没有办法从外部告诉它“嘿伙计,醒醒!”,以便我可以在合理的时间内加入它?

我绝对不是线程方面的专家,所以如果可能的话不要假设任何东西。

最佳答案

不,使用标准库中的线程是不可能的。

一种可能的解决方法是使用 condition_variable::sleep_for 以及 mutex 和 bool 条件。

#include <mutex>
#include <thread>
#include <condition_variable>

std::mutex mymutex;
std::condition_variable mycond;
bool flag = false;

void sleepy() {
std::unique_lock<std::mutex> lock(mymutex);
mycond.wait_for( lock,
std::chrono::seconds(1000),
[]() { return flag; } );
}

int main()
{
std :: thread sleepy_thread(sleepy);

{
std::lock_guard<std::mutex> lock(mymutex);
flag = true;
mycond.notify_one();
}

sleepy_thread.join();
}

或者,您可以使用 Boost.Thread库,它实现了中断点概念:

#include <boost/thread/thread.hpp>

void sleepy()
{
// this_thread::sleep_for is an interruption point.
boost::this_thread::sleep_for( boost::chrono::seconds(1000) );
}

int main()
{
boost::thread t( sleepy );

t.interrupt();
t.join();

}

关于c++ - 从 usleep 中唤醒一个 std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233019/

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