Rishi singh
Rishi singh

Reputation: 13

why THREADS in C++ gives different output on execution?

here is my code of thread programing. I am initializing the two thread like first thread t1 is initialized using the non member function of class person and 2nd thread t2 is initialized using a member function of person class. Now my doubt is why output is different at each time.

class person {
    int a;
public:
    person();
    person(int a):a(a){}

    void  pmemberfun() {
        cout << a;
    }    
};

void  func1() {
    cout << "\n fun1 \n";
}

int main() {
    thread t1(func1);
    //non member fun of class
    cout << "\nmain()\n";
    if (t1.joinable()) {
        t1.join();
        cout << "\njoiined1\n";
    } else {
        cout << "\nnot joinable";
    }

//using member function of class
    person a(10);
    thread t2(&person::pmemberfun, a);
    cout << "\nmain()\n";
    if (t2.joinable()) {
        t2.join();
        cout << "\njoiined\n";    
    } else {
        cout << "not joinable";
    }

the output when executed 1st time-

main()
 fun1
joiined 1
10
main()
joiined 2

and output when 2nd time execution is

 fun1
main()
joiined 1
10
main()
joiined 2

Upvotes: 1

Views: 167

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

When you do

thread t1(func1);
//non member fun of class
cout << "\nmain()\n";

You basically have

cout << "\n fun1 \n";
cout << "\nmain()\n";

But since cout << "\n fun1 \n"; is inside a thread it may or may not be executed before cout << "\nmain()\n"; is. You have the same thing for

thread t2(&person::pmemberfun, a);
cout << "\nmain()\n";

and even cout << "\nnot joinable"; might print before what the thread is supposed to print since if (t1.joinable()) could be evaluated before the thread even prints. The only lines that will not get executed out of order are cout << "\njoiined1\n"; since they can only happen after the thread ends.

Upvotes: 3

Related Questions