我正在将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_编程,以销毁已取消线程的所有对象......
例如,标准说当线程结束时,变量将被销毁。如果您取消线程,这对编译器来说将更加困难,如果不是不可能的话。
因此,如果您可以以某种方式避免它,我建议您不要取消线程。编写一个标准的轮询循环,使用条件变量,监听信号以中断读取等等 - 并定期结束线程。