mardi 4 octobre 2022

Why do the values of variables change in this multi-threaded program? [duplicate]

I have written a simple multi-threaded program as follows:

#include <thread>
#include <unistd.h>
#include <iostream>

using std::cout;
using std::endl;
using std::thread;

class TA
{
    public:
        int &m_i;
        TA(int &i) : m_i(i)
        {
            cout <<  "TA constructor is executed!" << endl;
            cout << m_i << endl;
        }
        TA(const TA &ta) : m_i(ta.m_i)
        {
            cout << "TA copy constructor is executed!" << endl;
            cout << m_i << endl;
        }
        ~TA()
        {
            cout << "TA destructor is executed!" << endl;
        }
        void operator()(){
            cout << "the value of m_i1: " << m_i << endl;
            cout << "the value of m_i2: " << m_i << endl;
            cout << "the value of m_i3: " << m_i << endl;
            cout << "the value of m_i4: " << m_i << endl;
            cout << "the value of m_i5: " << m_i << endl;
            cout << "the value of m_i6: " << m_i << endl;
        };
};

int main()
{
    int m = 9;
    TA ta(m);
    thread myobj(ta);
    myobj.detach();
    cout << "Hello world" << endl;
}

One possible result of the execution of this procedure is as follows:

TA constructor is executed!
9
TA copy constructor is executed!
9
Hello world
TA destructor is executed!
the value of m_i1: 0
the value of m_i2: 0
the value of m_i3: 0
the value of m_i4: 0
the value of m_i5: 0
the value of m_i6: 0
TA destructor is executed!

When I use gdb to debug, the value of m_i is shown as 9, but here it is 0. I don't quite understand it, the value of m_i should be 9.

Aucun commentaire:

Enregistrer un commentaire