简体   繁体   English

线程类无法正常工作

[英]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: 您需要了解线程的一些基本概念:

thread.detach( ) thread.detach()
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 . 如果两个线程都具有相同的thread id则它们是“可加入的”。 And It becomes 'NOT Joinable' once you called join method or detach method.! 而且,一旦您调用join方法或detach方法,它就会变成“ NOT Joinable”。

Problem 问题

You called thread.detach() first, which will separate the thread from main thread. 首先调用thread.detach() ,它将线程与主线程分开。 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 . 然后,您再次尝试将其join ,这将产生错误,因为两个线程是分开的,并且具有不同的thread id ,因此无法thread id

Solution

Either use join or use detach . 使用joindetach Don't use both of them. 不要同时使用它们。

  1. Join 加入
    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. Detach 分离
    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: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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