簡體   English   中英

如何從自身加入std :: thread(在C ++ 11中)

[英]How to join a std::thread from itself (in C++11)

我有一個std::thread等待和從套接字讀取。 並且有一個指向該thread的指針存儲在某個地方。 但是,當發生不好的情況並且thread結束時,我希望它調用導致結果的函數,該函數將加入該線程,然后刪除引用該線程的指針。 (我可以從線程內訪問該指針)

我可以在另一個線程中執行此操作,但是那個新線程就成了問題。

更改您的設計,以便您沒有這種奇怪的要求。 一個簡單的解決方案是對一個擁有線程並具有其他狀態信息的控制結構使用shared_ptr 線程可以將shared_ptr保留到此控件結構,並使用它向其他任何感興趣的代碼報告其狀態。 當沒有人關心這個線程時,此控制結構的最后一個shared_ptr將消失並被銷毀。

您可以在分離狀態下創建線程,並使線程生存期與條件變量相關,並在完成時切換布爾狀態。

#include <thread>
#include <iostream>
#include <unistd.h>
#include <condition_variable>
#include <mutex>

class A {
    private:
        void Threadfunction();
        volatile bool class_running;
        volatile bool thread_running;
        std::condition_variable cv;
        std::mutex mu;
    public:
        A();
        ~A();
        void Stop();
};
A::A(){
    class_running = true;
    thread_running = false;
    std::thread t(&A::Threadfunction,this);
    t.detach();
}
A::~A(){
    if(class_running) {this->Stop();}
}
void A::Stop() {
    std::unique_lock<std::mutex> lk(mu);
    class_running = false;
    while(thread_running) {
        cv.wait(lk);
    }
    std::cout << "Stop ended " << std::endl;
}
void A::Threadfunction(){
    thread_running = true;
    std::cout << "thread started " << std::endl;
    while(class_running){
        // Do something
    }
    thread_running = false;
    cv.notify_one();
    std::cout << "thread stopped " << std::endl;
}
int main(){
    A a1;
    A a2;
    sleep(1);
    std::cout << "a1.Stop() called " << std::endl;
    a1.Stop();
    sleep(1);
    std::cout << "a2.Stop() not called but a2 goes out of scope and destructor is called " << std::endl;
}

暫無
暫無

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

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