Maxwell Powell Maxwell Powell - 1 month ago 11
C Question

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

Answer

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 ()
{
  printf("hello");
}
Comments