簡體   English   中英

如何終止std :: thread?

[英]How to terminate a std::thread?

我當前正在開發一個程序,該程序需要從套接字服務器下載一些圖像,並且下載工作將執行很長時間。 因此,我創建了一個新的std::thread來執行此操作。

一旦下載, std::thread將調用當前Class的成員函數,但是該Class可能已經發布。 所以,我有一個例外。

如何解決這個問題呢?

void xxx::fun1()
{
   ...
}
void xxx::downloadImg()
{
 ...a long time
  if(downloadComplete)
  {
   this->fun1();
  }
}
void xxx::mainProcees()
{
  std::thread* th = new thread(mem_fn(&xxx::downloadImg),this);
  th->detach();
  //if I use th->join(),the UI will be obstructed
}

不要拆線。 取而代之的是,您可以擁有一個數據成員,該成員持有一個指向thread的指針,並將該線程join到析構函數中。

class YourClass {
public:
    ~YourClass() {
        if (_thread != nullptr) {
            _thread->join();
            delete _thread;
        }
    }
    void mainProcees() {
        _thread = new thread(&YourClass::downloadImg,this);
    }
private:
    thread *_thread = nullptr;
};

更新

就像@milleniumbug指出的那樣,您不需要動態分配thread對象,因為它是可移動的。 因此,另一個解決方案如下。

class YourClass {
public:
    ~YourClass() {
        if (_thread.joinable())
            _thread.join();
    }
    void mainProcess() {
        _thread = std::thread(&YourClass::downloadImg, this);
    }
private:
    std::thread _thread;
};

暫無
暫無

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

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