【问题标题】:Multithreading in C/C++ without waiting for the thread to finishC/C++ 中的多线程,无需等待线程完成
【发布时间】:2019-04-26 18:46:21
【问题描述】:

我看到的所有关于多线程的例子都是在main方法中使用这个方法来等待线程完成:

 pthread_join(thread_id, NULL); 

但是如果我不想让它等待呢?我希望我的 main 函数在线程正在工作时继续,但同时,我不希望 main 在线程存在之前退出。这在 C/C++ 中可行吗?

【问题讨论】:

  • 所以,在从main 退出之前,您想通过加入它来等待线程完成,对吧?
  • 是的,但我想在joining 之后运行代码,我不想等到线程完成。上面的代码会锁定mian,直到线程完成。
  • 不,你想在从 main 返回之前加入,这样 - 线程启动后的代码将与线程并行执行
  • 看看为什么教程没有提到这个?我认为除非您join,否则线程不会开始运行。谢谢你告诉我,我试试看。
  • 只需阅读有关pthread_createfunction starts a new thread in the calling process的手册

标签: c multithreading


【解决方案1】:

如果您想避免使用pthread_join(),则可以选择pthread_detach()。 来自man-page

int pthread_detach(pthread_t 线程);

pthread_detach() 函数标记由 thread 标识的线程 作为分离。当一个分离的线程终止时,它的资源是
无需自动释放回系统
另一个线程加入终止线程。

它不会阻止线程被 如果进程使用 exit(3) 终止(或等效地, 如果主线程返回)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多