0

I have a simpale program that should create two threads with a function hundler that will run infnite and a main thread.

Whenever I try to do pthread_join or pthread_exit to the main thread (in order to demonstrate that the children threads are still working after pthread_exit from main) there is never seems to be a context switch back to the main thread in order to print the message saying he is ending his job "Goodbye" (even the goodbye message before the thread creation is not printed, so I am not exactly sure what is the problem).Only the function handlers of the threads are printing what they should. I set sleep of 4 secs in the other threads in order to see this message before they start, there should have been a context switch to the only thread available that isn't sleeping (main)..

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread(void *vargp) {

sleep(4);
while(1)
    printf("First Thread No' %ld\n",pthread_self());

}

void *thread2(void *vargp) {
sleep(4);
while(1)
    printf("Second Thread No' %ld\n",pthread_self());

}


int main() {
int j,i = 42;
pthread_t tid, tid2;
printf("Good bye1");
pthread_create(&tid, NULL, thread, (void*)&i);
pthread_create(&tid2, NULL, thread2, (void*)&i);
printf("Good bye");
pthread_exit(NULL);
//pthread_join(tid, (void**)&i);
//pthread_join(tid2, (void**)&j);

}
Ben J
  • 137
  • 11
  • 1
    Probably: try adding a `\n` to your messages, or flushing stdout. – Mat Feb 11 '19 at 16:21
  • /n did work.. Can you explain why it did such a difference ? – Ben J Feb 11 '19 at 16:23
  • https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – Mat Feb 11 '19 at 16:26
  • google search "stdout buffering pthread site:stackoverflow.com" will lead you to other interesting info about all this – Mat Feb 11 '19 at 16:26

0 Answers0