I am recently learning about threads in C, and I have noticed something I consider weird. Let's take the next code:
#include <stdio.h>
#include <pthread.h>
void *sub_routine(void *p)
{
p = NULL;
printf("This is a sub_routine\n");
return (NULL);
}
int main(int argc, char **argv)
{
void *p;
pthread_t thread;
if (argc < 1)
return (0);
p = argv[1];
pthread_create(&thread, NULL, sub_routine, NULL);
sub_routine(p);
return (0);
}
I use this command line to compile my program:
gcc -Wall -Wextra -Werror -pthread pthreads.c
The expected result is to print This is a sub_routine
two times. Well that happens but not 100% of the times. Is there any particular reason for that?
CodePudding user response:
When main
returns, it exits the program even if other threads are running. Therefore, it’s possible for the thread you spawned to not get to the printf
before the main thread returns, in which case the program ends before you’ll see both messages.
One way to address this is to add a call to pthread_join
at the end of main
to tell the program to wait for the thread you created to finish running before main returns. That will ensure you always see two printouts.
CodePudding user response:
Add pthread_join(thread, NULL) at the end (just before return) of the main thread to join the thread "sub_routine"
The modified version of your code works properly:
#include <stdio.h>
#include <pthread.h>
void *sub_routine(void *p)
{
p = NULL;
printf("This is a sub_routine\n");
return (NULL);
}
int main(int argc, char **argv)
{
void *p;
pthread_t thread;
if (argc < 1)
return (0);
p = argv[1];
pthread_create(&thread, NULL, sub_routine, NULL);
sub_routine(p);
pthread_join(thread, NULL);
return (0);
}