P.S.
P.S.

Reputation: 384

Posix Thread Hangs after other threads exit?

3 threads:

pthread_create(&thread1, 
               &NULL,        
               Thread1,
               NULL);
pthread_create(&thread2, 
               &NULL,        
               Thread2,
               NULL);
pthread_create(&thread3, 
               &NULL,        
               Thread3,
               NULL);

printf("\n\nThreads Created\n");

    pthread_join(thread1,0);
    printf("Joined Thread1\n");

    pthread_join(thread2,0);
    printf("Joined Thread2\n");

    pthread_join(thread3,0);
    printf("Joined Thread3\n");

The 3 threads run for a while and based on the output to the console, appear to be working.

Eventually, thread 1 and 2 die after their work is done (appears correct as output from maint() "Joined Thread 1/2" is displayed)

Now, thread 3 still has some work to do and looks good. Then, close to processing it's last few items, it "appears" that thread 3 just hangs. It will be printing something out to the console and won't even finish the sentence.

Thread 3 has is a small sleep, locking and unlocking of a mutex (that thread 1 and 2 were using) and a conditional wait. Does not appear to be on the conditional wait as I print something out directly before it is called and do not see that.

It seems like it is the sleep, giving up the CPU but then never coming back.....?

Any other possibilities or reasons why?

Any solutions?

Thanks.

Upvotes: 1

Views: 334

Answers (1)

P.P
P.P

Reputation: 121427

As confirmed in the comments/chat, the problem is not that the thread 3 not printing any output but the output being buffered by printf().

You could use fflush() to flush it, or use \n to flush stdout as it's usually line-buffered.

Or you can disable the buffering altogether by using setbuf().

setbuf(stdout, NULL);

Upvotes: 2

Related Questions