溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中為什么gsl::joining_thread好于std::thread

發(fā)布時間:2021-11-25 15:56:28 來源:億速云 閱讀:135 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“C++中為什么gsl::joining_thread好于std::thread”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“C++中為什么gsl::joining_thread好于std::thread”吧!

CP.25: gsl::joining_thread好于std::thread

Reason(原因)

joining_thread是一種在和作用域連結(jié)的線程。分離之后的線程很難監(jiān)控。很難保證分離之后(或者存在潛在的分離可能性)的線程中不存在錯誤。

Example, bad(反面示例)

void f() { std::cout << "Hello "; }

struct F {
   void operator()() const { std::cout << "parallel world "; }
};

int main()
{
   std::thread t1{f};      // f() executes in separate thread
   std::thread t2{F()};    // F()() executes in separate thread
}  // spot the bugs
Example(示例)
void f() { std::cout << "Hello "; }

struct F {
   void operator()() const { std::cout << "parallel world "; }
};

int main()
{
   std::thread t1{f};      // f() executes in separate thread
   std::thread t2{F()};    // F()() executes in separate thread

   t1.join();
   t2.join();
}  // one bad bug left
Note(注意)

Make "immortal threads" globals, put them in an enclosing scope, or put them on the free store rather than detach(). Don't detach.

將“永遠(yuǎn)有效的線程"定義為全局的,將它們限制在一個封閉的作用域,或者將它們放在自由存儲中而不是分離它們。不要分離線程。

Note(注意)

Because of old code and third party libraries using std::thread, this rule can be hard to introduce.

因為舊代碼和第三方庫在使用std::thread,本準(zhǔn)則很難推廣。

Enforcement(實施建議)

Flag uses of std::thread:

標(biāo)記使用std::thread的代碼:

  • Suggest use of gsl::joining_thread or C++20 std::jthread.

  • 建議使用gsl::joining_thread或者C++20引入的std::jthread.

  • Suggest "exporting ownership" to an enclosing scope if it detaches.

  • 如果需要分離線程,建議“輸出所有權(quán)”到封閉的作用域。

  • Warn if it is not obvious whether a thread joins or detaches.

  • 如果不好判斷線程會連結(jié)還是分離,報警。

到此,相信大家對“C++中為什么gsl::joining_thread好于std::thread”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI