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;
}
Was it helpful?

Solution

The behaviour of pthreads which are not joined is undefined. The inconsistency vanishes if you join pthreads at the end of the main function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top