在多线程方案中,使用指针参数而不是引用具有不同的行为。当在单独的线程中进行更改时,值的确会在函数调用的中间更改。我正在寻找一种解释,以解释为什么引用引用和指针传递之间的行为不同。
下面的一些伪代码。将value
中的PrintValue
的参数类型更改为指针,第二次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();
}
答案 0 :(得分:1)
std::bind
将复制任何作为引用传递的内容。您需要使用std::reference_wrapper
和/或std::ref
,例如:
std::thread t(std::bind(&PrintValue, std::ref(a), &condVar));