C++11多線程join()和detach()的理解


簡介
每一個程序至少擁有一個線程,那就是執行main()函數的主線程,而多線程則是出現兩個或兩個以上的線程並行運行,即主線程和子線程在同一時間段同時運行。而在這個過程中會出現幾種情況:

主線程先運行結束
子線程先運行結束
主子線程同時結束
在一些情況下需要在子線程結束后主線程才能結束,而一些情況則不需要等待,但需注意一點,並不是主線程結束了其他子線程就立即停止,其他子線程會進入后台運行

join()
join()函數是一個等待線程完成函數,主線程需要等待子線程運行結束了才可以結束

#include <iostream>
#include <thread>
using namespace std;

void func()
{
  for(int i = -10; i > -20; i--)
  {
    cout << "from func():" << i << endl;
  }
}

int main() //主線程
{
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  thread t(func); //子線程
  t.join(); //等待子線程結束后才進入主線程
  return 0;
}


#include <iostream>
#include <thread>
using namespace std;

void func()
{
  for(int i = -10; i > -20; i--)
  {
    cout << "from func():" << i << endl;
  }
}

int main() //主線程
{
  thread t(func); //子線程
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  t.join(); //等待子線程結束后才進入主線程
  return 0;
}


#include <iostream>
#include <thread>
using namespace std;

void func()
{
  for(int i = -10; i > -20; i--)
  {
    cout << "from func():" << i << endl;
  }
}

int main() //主線程
{
  thread t(func); //子線程
  t.join(); //等待子線程結束后才進入主線程
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  return 0;
}


detach()函數
稱為分離線程函數,使用detach()函數會讓線程在后台運行,即說明主線程不會等待子線程運行結束才結束
通常稱分離線程為守護線程(daemon threads),UNIX中守護線程是指,沒有任何顯式的用戶接口,並在后台運行的線程。這種線程的特點就是長時間運行;線程的生命周期可能會從某一個應用起始到結束,可能會在后台監視文件系統,還有可能對緩存進行清理,亦或對數據結構進行優化。另一方面,分離線程的另一方面只能確定線程什么時候結束,發后即忘(fire andforget)的任務就使用到線程的這種方式

#include <iostream>
#include <thread>
using namespace std;

void func()
{
  for(int i = -10; i > -20; i--)
  {
    cout << "from func():" << i << endl;
  }
}

int main() //主線程
{
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  thread t(func); //子線程
  t.detach(); //分離子線程
  return 0;
}

可以明顯看到,主線程太快了,還沒等子線程運行就結束了

#include <iostream>
#include <thread>
using namespace std;

void func()
{
  for(int i = -10; i > -20; i--)
  {
    cout << "from func():" << i << endl;
  }
}

int main() //主線程
{
  thread t(func); //子線程
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  t.detach(); //分離子線程
  return 0;
}

同樣沒等子線程運行完就結束了

#include <iostream>
#include <thread>
using namespace std;

void func()
{
  for(int i = -10; i > -20; i--)
  {
    cout << "from func():" << i << endl;
  }
}

int main() //主線程
{
  thread t(func); //子線程
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  cout << "mian()" << endl;
  t.detach(); //分離子線程
  return 0;
}

沒等子線程運行完就結束

總結
join()函數是一個等待線程函數,主線程需等待子線程運行結束后才可以結束(注意不是才可以運行,運行是並行的),如果打算等待對應線程,則需要細心挑選調用join()的位置
detach()函數是子線程的分離函數,當調用該函數后,線程就被分離到后台運行,主線程不需要等待該線程結束才結束
————————————————
版權聲明:本文為CSDN博主「螞蟻的希望」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_36784975/article/details/87699113


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM