zoukankan      html  css  js  c++  java
  • 起thread时,运行报错terminate called without an active exception

    I am getting a C++ error with threading:

    terminate called without an active exception
    Aborted

    How to reproduce that error:

     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <string>
     4 #include <thread>
     5 using namespace std;
     6 void task1(std::string msg){
     7   cout << "task1 says: " << msg;
     8 }
     9 int main() { 
    10   std::thread t1(task1, "hello"); 
    11   return 0;
    12 }

    Compile and run:

    el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
    el@defiant ~/foo4/39_threading $ ./s
    terminate called without an active exception
    Aborted (core dumped)

    You get that error because you didn't join or detach your thread.

    One way to fix it, join the thread like this:

    #include <iostream>
    #include <stdlib.h>
    #include <string>
    #include <thread>
    using namespace std;
    void task1(std::string msg){
      cout << "task1 says: " << msg;
    }
    int main() { 
      std::thread t1(task1, "hello"); 
      t1.join();
      return 0;
    }

    Then compile and run:

    el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
    el@defiant ~/foo4/39_threading $ ./s
    task1 says: hello

    The other way to fix it, detach it like this:

    #include <iostream>
    #include <stdlib.h>
    #include <string>
    #include <unistd.h>
    #include <thread>
    using namespace std;
    void task1(std::string msg){
      cout << "task1 says: " << msg;
    }
    int main() 
    { 
         {
    
            std::thread t1(task1, "hello"); 
            t1.detach();
    
         } //thread handle is destroyed here, as goes out of scope!
    
         usleep(1000000); //wait so that hello can be printed.
    }

    Compile and run:

    el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
    el@defiant ~/foo4/39_threading $ ./s
    task1 says: hello

    Read up on detaching C++ threads and joining C++ threads.

    总之,就是线程还在运行,主进程就退出导致了该错误。

    原文链接:https://stackoverflow.com/questions/7381757/c-terminate-called-without-an-active-exception

  • 相关阅读:
    遇到的相关问题总结
    AI测试相关文章
    常用模块文档地址
    09-微服务接口:怎么用Mock解决混乱的调用关系
    03-思维方式:用一个案例彻底理解接口测试的关键逻辑
    1-基础:跳出细节看全局,接口测试到底是在做什么?
    21-Python并发编程之Futures
    使用原生php读写excel文件
    在for、foreach循环体中添加数组元素
    eval函数的坑
  • 原文地址:https://www.cnblogs.com/ranson7zop/p/8028799.html
Copyright © 2011-2022 走看看