取消 std::线程使用 native_handle() + pthread_cancel()
cancelling std::thread using native_handle() + pthread_cancel()
我正在将pthreads周围的先前线程包装器转换为std::thread。但是,c++11 没有任何方法可以取消线程。尽管如此,我还是需要取消线程,因为它们可能在外部库中执行非常冗长的任务。
我正在考虑使用在我的平台中提供pthread_id native_handle。我在Linux(Ubuntu 12.10)中使用gcc 4.7。这个想法是:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main(int argc, char **argv) {
cout << "Hello, world!" << endl;
auto lambda = []() {
cout << "ID: "<<pthread_self() <<endl;
while (true) {
cout << "Hello" << endl;
this_thread::sleep_for(chrono::seconds(2));
}
};
pthread_t id;
{
std::thread th(lambda);
this_thread::sleep_for(chrono::seconds(1));
id = th.native_handle();
cout << id << endl;
th.detach();
}
cout << "cancelling ID: "<< id << endl;
pthread_cancel(id);
cout << "cancelled: "<< id << endl;
return 0;
}
线程被 pthreads 引发的异常取消。
我的问题是:
这种方法会有任何问题(除了不可移植)吗?
不,我认为您不会遇到以下其他问题:
- 不便携
- 必须仔细_very_very_编程,以销毁已取消线程的所有对象......
例如,标准说当线程结束时,变量将被销毁。如果您取消线程,这对编译器来说将更加困难,如果不是不可能的话。
因此,如果您可以以某种方式避免它,我建议您不要取消线程。编写一个标准的轮询循环,使用条件变量,监听信号以中断读取等等 - 并定期结束线程。
相关文章:
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 直接读取 pthread 互斥锁的所有者字段是否安全?
- 为什么 pthread 会减慢代码速度?
- 对 pthread CLion 的未定义引用
- C++ 17:pthread的生成文件标志
- 将带有结构的参数传递给 pthread
- Posix 线程类和启动例程 (pthread)
- 在 pthread 中使用共享变量