gpt4 book ai didi

c++ - 使用 native_handle() + pthread_cancel() 取消 std::thread

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:18:52 24 4
gpt4 key购买 nike

我正在将之前围绕 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 抛出的异常取消。

我的问题是:

这种做法会不会有什么问题(除了不可移植)?

最佳答案

不,我认为您不会遇到以下问题:

  • 不可携带
  • 必须_非常_非常_仔细地编程以销毁已取消线程的所有对象...

例如,标准说当一个线程结束时,变量将被销毁。如果您取消一个线程,这对编译器来说将更加困难,如果不是不可能的话。

因此,我建议不要取消一个线程,如果你能以某种方式避免的话。编写一个标准的轮询循环、使用条件变量、监听中断读取的信号等等——并定期结束线程。

关于c++ - 使用 native_handle() + pthread_cancel() 取消 std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531241/

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