Maxwell Powell
Maxwell Powell

Reputation: 143

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

Upvotes: 0

Views: 194

Answers (3)

Bambang
Bambang

Reputation: 401

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

Upvotes: 1

cpatricio
cpatricio

Reputation: 457

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

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182865

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.

Upvotes: 2

Related Questions