代码之家  ›  专栏  ›  技术社区  ›  VincentDM

无法修改其他线程中引用传递的值

  •  2
  • VincentDM  · 技术社区  · 8 年前

    我试图向一个同事演示为什么您最好将const引用传递给使用以下代码执行只读操作的函数。令我惊讶的是,它印着“它很安全!”,即使我正在更改 passedBool 当另一个线程正在休眠时。

    我想知道我是否在某个地方输入了错别字,编译器是否优化了代码并通过了 通行工具 通过复制来避免一些开销,或者如果启动另一个线程会创建 通行工具 .

    class myClass
    {
    public:
      myClass(bool& iBool)
      {
        t = thread(&myClass::myMethod,this,iBool);
      }
    
      ~myClass()
      {
        t.join();
      }
    
    private:
      thread t;
    
      void myMethod(bool& iBool)
      {
        this_thread::sleep_for(chrono::seconds(1));
    
        if(iBool)
          cout << "It's safe!" << endl;
        else
          cout << "It's NOT safe!!!" << endl;
      }
    };
    
    
    void main()
    {
      bool passedBool = true;
    
      cout << "Passing true" << endl;
      myClass mmyClass(passedBool);  
    
      cout << "Changing value for false" <<endl;
      passedBool = false;
    
      cout << "Expect \"It's NOT safe!!!\"" <<endl;
    }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   wtom    8 年前

    线程函数的参数按值移动或复制。如果 引用参数需要传递给线程函数,它具有 被包装(STD::REF或STD::CREF)。

    from here