难以理解*和&当他们带来线程

时间:2015-06-24 17:32:26

标签: c++ multithreading pointers pass-by-reference

所有!我遇到了一些麻烦!“改变”功能没有改变......

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;
}

所以,我写了另一个程序来跟踪“a”和“&amp; a”的地址。这是代码。

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;
}

结果:

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

似乎函数“更改”仅在我们将其作为线程运行时才起作用。

我想知道它是否与STACK有关?

有人能给我一些言论吗?非常感谢..这真的让我痛苦T_T

1 个答案:

答案 0 :(得分:2)

您遇到的问题是std :: thread没有通过引用获取a。您可以使用std::ref包装a以获取对线程函数的引用。

thread tt(change, std::ref(a));