簡體   English   中英

通過引用將參數傳遞給std :: thread函數是否安全?

[英]Is it safe to pass arguments by reference into a std::thread function?

#include <thread>
#include <string>
#include <vector>
#include <chrono>

using namespace std;

void f(const vector<string>& coll)
{
    this_thread::sleep_for(1h);

    //
    // Is coll guaranteed to be valid before exiting this function?
    //
}

int main()
{
    {
        vector<string> coll(1024 * 1024 * 100);
        thread(f, coll).detach();
    }

    //
    // I know std::thread will copy arguments into itself by default, 
    // but I don't know whether these copied objects are still valid
    // after the std::thread object has been destroyed.
    //

    while (true);
}

通過引用將參數傳遞給std :: thread函數是否安全?

作為@ TC的評論,你沒有傳遞對線程的引用,你只需在線程中復制一個向量:

thread(f, coll).detach(); // It's NOT pass by reference, but makes a copy.

如果你真的想通過引用傳遞,你應該這樣寫:

thread(f, std::ref(coll)).detach(); // Use std::ref to pass by reference

然后,如果線程試圖訪問向量,代碼將獲得段錯誤,因為當線程運行時,很可能向量已經被破壞(因為它超出了它在主程序中的范圍)。

所以對你的問題:

通過引用將參數傳遞給std::thread函數是否安全?

  • 如果你確定在線程運行期間對象仍然有效,那么這是安全的。
  • 如果物體被破壞是不安全的,你會得到段故障。
  • 在退出此功能之前, coll是否保證有效?

    • 更新:是的。 當你通過coll到的構造函數std::threadmain功能,是因為coll是一個對象,它是decay復制。 這個decay副本基本上move了向量(因此它變為rvalue),它將在執行線程期間綁定到f中的coll參數。 (感謝@Praetorian的評論)
  • 通過引用將參數傳遞給std::thread函數是否安全?

    • 你的論點decay復制,所以你卻從未通過引用傳遞任何東西std::thread
  • 參考std::decayhttp//www.cplusplus.com/reference/type_traits/decay/

  • 這個問題中的接受答案std :: thread帶有可移動的,不可復制的參數,解釋了傳遞給std::thread的參數會發生什么

暫無
暫無

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

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