簡體   English   中英

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

[英]cancelling std::thread using native_handle() + pthread_cancel()

我正在將一個先前的線程包裝器轉換為pthreads到std :: thread。 但是c ++ 11沒有任何方法可以取消該線程。 盡管如此,我要求取消線程,因為它們可能在外部庫中執行非常冗長的任務。

我正在考慮使用native_handle,它在我的平台上給了我pthread_id。 我在Linux中使用gcc 4.7(Ubuntu 12.10)。 這個想法是:

#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_,取消線程的所有對象都被銷毀...

例如,標准說當一個線程結束時,變量將被銷毀。 如果你取消一個線程,這對編譯器來說將更加困難,如果不是不可能的話。

因此,如果您可以以某種方式避免它,我建議不要取消線程。 編寫標准輪詢循環,使用條件變量,監聽信號以中斷讀取等等 - 並定期結束線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM