简体   繁体   中英

thread class doesn't work properly

relates to threads and parallel programming

i saw a question on thread which was answered by someone .i tried the code answered by him and wrote it. i tried

   #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;
   }

and i received output as

Hello world!!!!

that was printed only once i don't understand shouldn't it be more number of times

You need to understand some basic concepts for thread:


Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.

Two threads are 'Joinable' if they both have same thread id . And It becomes 'NOT Joinable' once you called join method or detach method.!

Problem

You called thread.detach() first, which will separate the thread from main thread. And then You are again trying to join it which will give Error because two threads can not be joined as they are separated and have different thread id .

Solution

Either use join or use detach . Don't use both of them.


  1. The function returns when the thread execution has completed.

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

  2. separates out the execution of both threads.

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

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM