使用pthread创建线程失败



当我运行test.o时,我正在用gcc test.c -o test.o -lpthread -lrt编译我的代码,没有打印到控制台。我已经阅读了手册页,我认为我的代码应该成功地创建一个新线程。是否有任何原因导致创建的线程不能打印到控制台?

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
void* thd ();
pthread_t tid;
int main()
{
  int i;
  i = pthread_create(&tid, NULL, &thd, NULL);
}
void* thd ()
{
  printf("hello");
}

它不会打印,因为你会在打印之前结束(没有join,你不会等待线程结束)

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
void* thd(void *);
pthread_t tid;
int main()
{
  int i;
  i = pthread_create(&tid, NULL, &thd, NULL);
  pthread_join(tid, NULL);
  return 0;
}
void* thd(void *unused)
{
  printf("hellon");
  return 0;
}

您的程序创建了一个线程,然后终止,从不给线程机会完成任何有用的工作。没有理由期望它打印任何东西

就像David Schwartz说的,主线程需要等待子线程完成。在main()中使用pthread_join来实现这一点,如下所示:

#include <sys/types.h>
void *thd(void *);
pthread_t tid;
int main()
{
  int i;
  i = pthread_create(&tid, NULL, &thd, NULL);
  pthread_join(tid, NULL);
  return 0;
}
void *thd(void *unused)
{
  printf("hellon");
  return 0;
}

最新更新