gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:58:39 26 4
gpt4 key购买 nike

这是我的代码:

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 Code NOT RUN 中,如果我使用 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++ - Centos 中的 pthread C++ 无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35081718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com