0

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;
}
pranith
  • 869
  • 9
  • 24
  • On what system does it do this? I can only get it to print twice. – Amardeep AC9MF May 02 '14 at 00:54
  • 1
    your code has undefined behavior, you never join or detach your thread. your main thread terminates earlier than created thread. – billz May 02 '14 at 00:55
  • Your output doesn't match the code. Where is the leading space on the thread's output? – Amardeep AC9MF May 02 '14 at 00:59
  • This is a linux system and I edited the output so that it shows up as code for SO. – pranith May 02 '14 at 01:38
  • @billz you seem to be right. After I add a pthread_join in the main function this behaviour does not repeat. – pranith May 02 '14 at 01:41
  • 3
    See this related question: http://stackoverflow.com/questions/13550662/pthread-one-printf-statement-get-printed-twice-in-child-thread For some reason on Linux (maybe other systems?) an unjoined thread can cause the last line of output to be repeated when the process ends. I think that's a bug in the runtime, but other people seem to be of the opinion that ending a process with an unjoined thread results in an undefined or unspecified behavior situation that permits this. – Michael Burr May 02 '14 at 07:02

1 Answers1

0

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

pranith
  • 869
  • 9
  • 24