简体   繁体   English

使用pthread创建线程失败

[英]Failure creating threads with pthread

I'm compiling my code with gcc test.c -o test.o -lpthread -lrt when I run test.o nothing prints to the console. 运行test.o时,我正在使用gcc test.c -o test.o -lpthread -lrt编译代码。 I've read the man pages and I think that my code should successfully create a new thread. 我已经阅读了手册页,并且我认为我的代码应该成功创建一个新线程。 Would there be any reason that the created thread isn't able print to the console? 是否有任何原因导致创建的线程无法打印到控制台?

#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");
}

Your program creates a thread and then terminates, never giving the thread a chance to accomplish any useful work. 您的程序创建一个线程,然后终止,从不给线程机会完成任何有用的工作。 There's no reason it should be expected to print anything. 没有理由应该打印任何东西。

It wont print because you will end before the print (without join, you wont wait for the thread to end) 它不会打印,因为您将在打印之前结束(如果没有加入,则不会等待线程结束)

#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("hello\n");
  return 0;
}

Just like David Schwartz said, the main thread need to wait for the child thread to finish. 就像David Schwartz所说的那样,主线程需要等待子线程完成。 Use pthread_join inside main() to do that, like this: 在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("hello\n");
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM