【问题标题】:Changing value of variable passed by reference outside function call does not change value inside function更改函数调用外部引用传递的变量的值不会更改函数内部的值
【发布时间】:2020-10-22 17:55:01
【问题描述】:

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

下面的一些伪代码。将PrintValue 内的value 的参数类型更改为指针,第二个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();
}

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2016-03-28
    相关资源
    最近更新 更多