在函数调用外部更改引用传递的变量的值不会更改函数内部的值



然而,在多线程场景中,使用指针参数而不是引用会有不同的行为。当在单独的线程中更改时,该值在函数调用的中间确实发生了更改。我正在寻找一个解释,解释为什么通过引用传递和通过指针传递的行为不同。

下面的一些伪代码。将PrintValuevalue的参数类型更改为指针,第二次EXPECT_EQ测试将失败,因为在等待通知时实际更改了值。

void PrintValue(int& value, ConditionVariable* condVar) {
EXPECT_EQ(value, 5);
condVar->WaitFor(std::chrono::milliseconds(100));
EXPECT_EQ(value, 5); // will pass unless value is passed as pointer
}
TEST(MyTest, MyTestOnReference) {
int a = 5;
int* ptr_a = &a;
ConditionVariable condVar;
std::thread t(std::bind(&PrintValue, a, &condVar));
milliSleep(25);
*ptr_a = 50000; // change value of a while PrintValue is waiting for notification.
condVar.Notify();
t.join();
}

std::bind将复制作为引用传递的任何内容。您需要使用std::reference_wrapper和/或std::ref,例如:

std::thread t(std::bind(&PrintValue, std::ref(a), &condVar));

最新更新