簡體   English   中英

重用線程-Boost與STD線程行為

[英]Reusing a thread - boost vs std thread behaviour

我似乎在boost和std線程之間得到了不同的線程對象分配行為。 如果我使用增強線程,則可以重新分配線程成員變量並重新創建線程。 如果使用std線程, terminate called without an active exception運行時錯誤terminate called without an active exception

這是有問題的代碼(運行,然后將boost ::替換為std::)

class ThreadTest 
 {
    private:
    std::thread mythread;
    std::atomic<bool> running_;

    int doSomeWork(){
        int i=0;
        cout << "starting" << endl;
        while(running_){
            cout << "working" << endl;
            std::this_thread::sleep_for (std::chrono::seconds(1));
            if (i>3){ break; } else { i++; }
        }
        running_ = false;
    }

    public:
    void runThread(){
        running_ = true;
        mythread = std::thread(&ThreadTest::doSomeWork, this);
    }

    void joinThread(){
        mythread.join();
    }
 };

int main(){ 
    ThreadTest test;
    test.runThread();
    std::this_thread::sleep_for (std::chrono::seconds(10));
    test.runThread();
    test.joinThread();
    return 0;
 }

提升輸出:

starting
working
working
working
working
working
starting
working
working
working
working
working

std的輸出::

starting
working
working
working
working
working
terminate called without an active exception
Aborted (core dumped)

這一段特定的代碼在似乎沒有增強依賴關系的庫中使用。 我想保持這種方式,那么有沒有辦法使用std線程獲得增強的“重新分配”行為?

編輯-解決方案

我添加了一個std::atomic<bool> threadInitialized_; 到在線程函數doSomeWork()設置為true的類。 我的runThread()方法變為:

void runThread(){
    if(threadInitialized_)
       mythread.join();

    running_ = true;
    mythread = std::thread(&ThreadTest::doSomeWork, this);
}

我知道這將阻塞主線程,直到生成線程完成。

來自std :: thread :: operator =()

“如果[線程對象]是可連接的,則調用terminate()。”

通常,正如上面正確指出的那樣,所有(可連接)線程都需要在銷毀對象之前進行連接或分離。

現在,Boost線程與std :: thread之間的(眾多)區別之一是Boost線程將自己分離到其析構函數中,而std :: thread則不會。 您對std :: thread的不正確使用會因此正確觸發Terminate()。

PS:請勿(!!)相信std :: threads和boost :: thread上方的其他評論程序應具有“相同”的功能-這只是不正確!

在使用boost :: thread時,如果您未顯式調用join()或detach(),則boost :: thread析構函數和賦值運算符將分別對要銷毀/分配給其的線程對象調用detach()。 對於C ++ 11 std :: thread對象,這將導致對std :: terminate()的調用並中止應用程序。 在這種情況下,您必須手動調用detach()或join()。

暫無
暫無

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

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