自动终止 C++11 STL 线程
Auto-terminate C++11 STL thread
我希望 STL 线程在完成它应该做的事情后自行终止;另外,有没有办法知道线程何时完成?就像一个事件左右。
提前谢谢。
如果您想要一种方法来轮询线程的完成状态,而不是简单地使用 join
阻塞,您可以使用 async
生成您的线程,并通过等待 0 超时来轮询返回的future
以完成:
void f() {
std::this_thread::sleep_for(std::chrono::seconds{2});
}
int main() {
auto const zero = std::chrono::seconds{0};
auto result = std::async(std::launch::async, f);
while (result.wait_for(zero) != std::future_status::ready) {
std::cout << "I'm still waiting...n" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds{100});
}
result.get();
std::cout << "Done.n";
}
线程在函数 f 结束后终止,并且:
void f()
{
do_some_work();
// end of function f
}
...
{
...
std::thread t(f);
do_some_other_work();
t.join();
}
函数join
->块是你当前的线程,直到线程 t 停止。
该操作称为join
: http://www.cplusplus.com/reference/thread/thread/join/
调用时,当前线程将等待另一个线程完成。就这么简单。而已。
就像斯维特洛夫娃和羽蛇神说的那样:使用连接操作来确保线程完成。
但是,如果您想知道线程何时完成,而不使用阻塞连接操作,则可以分离线程并使用一些全局变量来检查线程是否处于活动状态。伪代码:
std::atomic<bool> imdone;
void myThreadfunction() {
//dosomestuff;
imdone = true;
return;
}
int main() {
imdone = false;
std::thread t1(myThreadfunction);
t1.detach();
//dosomeotherstuff
while(!imdone) {
//dosomeotherstuffwhilethreadisrunning
}
}
但是,为要独立运行的每个线程使用全局变量并不是很好......
相关文章:
- 正确使用函子C++ STL 线程
- 重写 C++ STL 分配器函数以将其包装为线程安全
- C++STL(ExecutionPolicy)算法如何确定要使用多少并行线程
- 分割故障,可能的原因:功能指针,多线程,STL地图等
- C++STL多线程,并行运行计算
- 自动终止 C++11 STL 线程
- C++ stl unordered_map,线程安全,其中每个线程仅访问其自己分配的键,并且可以编辑该值
- C 11 STL容器和线程安全
- 关于多线程应用程序中的 STL 字符串异常
- stl或boost中是否存在用于线程间通信的线程安全结构,其行为类似于队列
- OpenMP线程、数据访问延迟和STL数据容器
- C++ STL 算法(列表排序)OpenMP/多线程实现
- C++ STL 向量迭代器与索引访问和线程安全
- 通过不同的线程使用迭代器遍历 STL 映射
- 选择 STL 容器来存储线程
- 抽象与线程相关的 STL 和 Boost 类型和方法
- 指向STL容器线程安全性(队列/取消队列)的指针
- Visual C++2010中STL映射的实现与线程安全
- 复制/修改STL容器的副本是线程安全的
- 在boost或stl线程安全容器中,类似于lists和unordered_maps