簡體   English   中英

從void方法啟動一個線程

[英]Starting a thread from a void method

使用C ++,我想從void方法啟動一個線程,然后在線程完成之前返回。 例如:

 #include <thread> using namespace std; void longFunc(){ //stuff } void startThread(){ thread t(longFunc); } int main(void){ startThread(); //lots of stuff here... return 0; } 

startThread()完成時,t嘗試刪除,並失敗。 我怎樣才能做到這一點?

如果你真的想要一個即發即棄模式,你可以從線程中分離出來:

void startThread(){
    thread t(longFunc);
    t.detach();
}

或者如果你需要加入線程(這通常是一個合理的東西),你可以簡單地按值返回一個std::thread對象(線程包裝器是可移動的):

std::thread startThread()
{
    return std::thread(longFunc);
}

無論如何,您可以考慮通過std::async()啟動線程並返回future對象。 這將是異常安全的,因為在啟動的線程中拋出的異常將被未來的對象吞噬,並在您調用get()時在主線程中再次拋出:

#include <thread>
#include <future>

void longFunc()
{
  //stuff
}

std::future<void> startThread()
{
    return std::async(std::launch::async, longFunc);
}

int main(void)
{
    auto f = startThread();
    //lots of stuff here...

    // For joining... (wrap in a try/catch block if you are interested
    //                 in catching possible exceptions)
    f.get();
}

暫無
暫無

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

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