0

Program:

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
void* pfun1(void *vargp);
void* pfun2(void *vargp);
void main(){
    int treturn,jreturn;
    pthread_t tid1,tid2;
    printf("Before thread call\n");
    treturn = pthread_create(&tid1,NULL,pfun1,NULL);
    treturn = pthread_create(&tid2,NULL,pfun2,NULL);
    jreturn = pthread_join(tid1,NULL);
    //jreturn = pthread_join(tid2,NULL);
    printf("After thread call\n");
}
void*  pfun1(void *vargp){
    int i;
    for(i=0;i<5;i++){
            printf("Thread1: %d\n",i);
            sleep(1);
    }
    return (void*)0;
}
void*  pfun2(void *vargp){
    int i;
    for(i=5;i<10;i++){
            printf("Thread2: %d\n",i);
            sleep(1);
    }
        return (void*)0;
}

In the above program, I joined only the first thread to the main program using pthread_join(). And the second thread is only created and not attached to main. But output function contains the output of the second thread too. How come it is possible to get the output of 2nd thread even though it is not attached to main?

Output:

Before thread call
Thread2: 5
Thread1: 0
Thread2: 6
Thread1: 1
Thread2: 7
Thread1: 2
Thread2: 8
Thread1: 3
Thread2: 9
Thread1: 4
After thread call
1
  • 1
    The pthread_join function is not to attach or launch the thread, it is used to wait for the thread to finish. Commented Mar 1, 2019 at 10:34

2 Answers 2

2

Joining is about synchronization (after a join, the joined thread is definitely finished) and obtaining the return value of the thread (the (void*)0s you're returning in each case).

It has nothing to do with IO redirection. Threads share the same stdout/stdin (as well as other filedescriptors and stdio buffers) and writes to (/reads from) those are immediate. They aren't postponed until the thread is joined.

Sign up to request clarification or add additional context in comments.

2 Comments

If threads share the same stdin/stdout means, why I can't get any output message if thread1 is not joined?
@mrg Returning from main kills all threads. Chances are they'll be killed before they manage to output anything. If I run it without the joins, I get outputs from the reads on some runs and not during others. It's timing sensitive.
0

As i can understand from this link pthread_join just wait for tid1 retrun inside main function, its not prevent tid2 from output. So i think, if you want run tid2 after tid1 just switch the lines:

treturn = pthread_create(&tid1,NULL,pfun1,NULL);
jreturn = pthread_join(tid1,NULL);
treturn = pthread_create(&tid2,NULL,pfun2,NULL);

Im not proffesional at this point, so you can make research for better solution if you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.