簡體   English   中英

線程類無法正常工作

[英]thread class doesn't work properly

與線程和並行編程有關

我看到一個線程問題,有人回答了。我嘗試了他回答的代碼並將其編寫。 我試過了

   #include <iostream>
   #include <thread>
   using namespace std;
   void printx()
   {
    cout << "Hello world!!!!"<< endl;
    cout << "Hello world!!!!"<< endl; 
    cout << "Hello world!!!!"<< endl; 
    cout << "Hello world!!!!"<< endl;  
   }
   int main(){
    cout << "Hello world!!!!"<< endl; 
    thread t1(printx);
    //t1.join();
    t1.detach();
    cout << "Hello world!!!!"<< endl; 
   t1.join();
   return 0;
   }

我收到的輸出為

你好,世界!!!!

那是只印過一次,我不明白應該不會印更多次

您需要了解線程的一些基本概念:

thread.detach()
將執行線程與線程對象分開,從而允許執行獨立地繼續。 線程退出后,將釋放所有分配的資源。

如果兩個線程都具有相同的thread id則它們是“可加入的”。 而且,一旦您調用join方法或detach方法,它就會變成“ NOT Joinable”。

問題

首先調用thread.detach() ,它將線程與主線程分開。 然后,您再次嘗試將其join ,這將產生錯誤,因為兩個線程是分開的,並且具有不同的thread id ,因此無法thread id

使用joindetach 不要同時使用它們。

  1. 加入
    線程執行完成后,該函數返回。

      void printx() { cout << "In thread"<< endl; } int main() { cout << "Before thread"<< endl; thread t1(printx); t1.join(); cout << "After Thread"<< endl; return 0; } 
  2. 分離
    分離出兩個線程的執行。

     void printx() { cout << "In thread"<< endl; } int main() { cout << "Before thread"<< endl; thread t1(printx); t1.detach(); cout << "After Thread"<< endl; return 0; } 

參考文獻:

暫無
暫無

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

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