简体   繁体   中英

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. 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. Use pthread_join inside main() to do that, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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