The behaviour of pthreads which are not joined is undefined. The inconsistency vanishes if you join pthreads at the end of the main function.
why does it print thrice when using pthreads?
Question
Consider the following snippet of code. It would be sane to guess that it would print atmost two numbers to standard output. But on some runs I get the following:
user@homedesk:test~> ./test
140641008801600
140640992085760
140640992085760
Why is it printing out three numbers?
#include <iostream>
#include <pthread.h>
static void* create_thread(void *ptr)
{
std::cout << " " << pthread_self() << std::endl;
while(1);
return NULL;
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, create_thread, NULL);
std::cout << pthread_self() << std::endl;
return 0;
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow