问题描述
我将一个以前的线程包装pthreads转换为std ::线程。
然而,c ++ 11没有任何方法来取消线程。
I am converting a previous thread wrapper around pthreads to std::thread.However c++11 does not have any way to cancel the thread. I REQUIRE, nonetheless, to cancel threads since they may be performing a very lengthy task inside an external library.
我正在考虑使用在我的平台上使用pthread_id的native_handle,但是我要求取消线程,因为它们可能在外部库中执行非常漫长的任务。 。我在Linux中使用gcc 4.7(Ubuntu 12.10)。这个想法是:
I was considering using the native_handle that gives me pthread_id in my platform. I'm using gcc 4.7 in Linux (Ubuntu 12.10). The idea would be:
#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抛出的异常取消。
The thread is canceled by an exception thrown by pthreads.
我的问题是:
这种方法有没有什么问题(除了不可移植)?
Will there be any problem with this approach (besides not being portable)?
推荐答案
不,我不认为你不会有额外的问题:
No, I don't think that you will not have additional problems than:
- 不能移动
- 必须仔细编程_very_very_,取消的话题的所有对象都将被销毁...
例如,标准说当一个线程结束变量将被销毁。如果你取消一个线程,这将是非常困难的编译器,如果不是不可能的。
For example, the Standard says that when a thread ends variables will be destroyed. If you cancel a thread this will be much harder for the compiler, if not impossible.
我会,因此建议不取消线程如果你能以某种方式避免它。写一个标准的轮询循环,使用一个条件变量,监听一个信号来中断读取等等 - 并定期结束线程。
I would, therefore recommend not to cancel a thread if you can somehow avoid it. Write a standard polling-loop, use a condition variable, listen on a signal to interrupt reads and so on -- and end the thread regularly.
这篇关于取消std ::线程使用native_handle()+ pthread_cancel()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!