如何让pthread在后台工作而不是阻塞shell?

Arj*_*ora 3 c multithreading

即使主进程退出,此代码中的子线程也会阻塞shell.如何让它在后台运行而不阻止shell?我认为这是可能的fork(),但我不想创建一个全新的过程.

谢谢.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void * myThreadFun (void *vargp)
{
  while (1)
    {
//Do useful work continuously
  sleep (1);
}
}

int
main ()
{
  pthread_t tid;
  pthread_create (&tid, NULL, myThreadFun, NULL);
  pthread_detach (tid);
  printf ("After Thread\n");
  pthread_exit (0);
}
Run Code Online (Sandbox Code Playgroud)

Dua*_*lly 6

在多线程程序中,主线程无法实际退出并使生成的线程继续运行.如果你需要这个程序在从shell执行它时继续运行但是立即返回shell提示符,即在后台运行,你将不得不使用fork().