c++ - pthread C++在Centos中无法运行

标签 c++ pthreads

这是我的代码:

void* task1(void* unused)
{
    try {               
      cout << "Run Thread" << endl;     
    }catch (const char* msg) {
      cout << msg << endl;
    }    
}

int main(int argc, char *argv[])
{   
    try {
      pthread_t thread_id;    
      int res = pthread_create(&thread_id, NULL, &task1, NULL);
      cout << res << std::endl;   
      exit(EXIT_SUCCESS);      
    }catch (const char* msg) {
      cout << msg << endl;
    }

}
  • 在 Ubuntu 中运行代码。
  • 在 CentOS 代码未运行中,如果我使用 pthread_join(thread_id, NULL); 代码已运行,但可以等待 pthread 完成。我尝试 pthread_tryjoin_np 但代码未运行。
  • 请帮我在 centos 上运行代码,不等了

最佳答案

如果程序main()在线程实际启动之前退出(并运行到点 cout << ... ),线程将被终止并且不再继续运行。

即您需要等待pthread_join()之前main()退出。

Ubuntu 中的情况纯粹是巧合,线程在 main() 之后被 C++ 运行时终止之前设法打印了该行。退出。

如果你不想等待,因为你想启动多个线程,你可以使用线程池(线程数组)。首先启动所有这些,然后 pthread_join()等待全部完成。

此外,如果 pthread_join()尽管线程终止但仍会阻塞,请确保您将线程创建为可连接的。这是默认值,因此请确保您没有将线程属性显式设置为 PTHREAD_CREATE_DETACHED .

为了绝对确定,您可以显式提供线程创建属性并确保线程被创建为可连接:

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread_id, &attr, &task1, NULL);
pthread_attr_destroy(&attr);
pthread_join(thread_id, NULL);

(不包括错误处理)

关于c++ - pthread C++在Centos中无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35081718/

相关文章:

c++ - 了解导入在 C++ 中的工作原理

c - 添加更多线程在什么时候停止帮助?

c++ - 我们是否需要保护单个赋值或 if 线程安全语句

c - 多线程 C 程序无法使用参数运行

函数 pthread_join 的代码 - Pthread 库

c++ - C/C++ pthread 信号和指针

c++ - 当文件无法打开时我应该关闭它吗?

c++ - View ::istream 或范围::istream_view 的语法是否正确?

c++ - 创建作为运算符(operator)工作的方法

c++ - 使用什么数据结构