1

all!I meet some trouble!The function "change" changes nothing...

void change(int &a){
    cout << "thread tt \t" << &a << " value:" << a << endl;
    a = 5;
    return;
}

int main()
{
    int a = 4;
    cout << "Thread main \t" << &a << " value:" << a << endl;
    thread tt(change, a);

    tt.join();
    cout << "After join() \t" << &a << " value:" << a << endl;

    return 0;
}

So, I write another programme to track the address of "a" and "&a".Here is the code.

void change(int &a,int b){
    cout << "thread change \t" << &a << " value:" << a << endl;
    a = b;
    return;
}


void change2(int *a,int b){
    cout << "thread change2 \t" << &a << " value:" << a << endl;
    *a = b;
    return;
}

int main()
{
    int a = 1;

    change(a,2);
    cout << &a << " " << a << endl;
    change2(&a,3);
    cout << &a << " " << a << endl;
    cout << "Thread main \t" << &a << " value:" << a << endl<<endl;


    thread t(change, a,4);
    t.join();
    cout << "After t.join()\t" << &a << " value:" << a << endl;
    cout << &a << " " << a << endl << endl;

    thread tt(change2, &a,5);
    tt.join();
    cout << "After tt.join()\t" << &a << " value:" << a << endl;
    cout << &a << " " << a << endl << endl;

    return 0;
}

And results:

thread change   0038FE98 value:1
0038FE98 2
thread change2  0038FD68 value:0038FE98
0038FE98 3
Thread main     0038FE98 value:3

thread change   0070FAF4 value:3
After t.join()  0038FE98 value:3
0038FE98 3

thread change2  00D0F99C value:0038FE98
After tt.join() 0038FE98 value:5
0038FE98 5

It seems that function "change" does NOT work only when we run it as a thread.

And I wonder whether it relates to STACK?

Could anyone give me some explenation?thanks a lot.. It really suffers me T_T

Jashaszun
  • 9,207
  • 3
  • 29
  • 57
Ven
  • 39
  • 1

1 Answers1

2

The issue you are having is that std::thread is not taking a by reference. You can wrap a with std::ref in order to get the reference to the thread function.

thread tt(change, std::ref(a));
NathanOliver
  • 171,901
  • 28
  • 288
  • 402