c++11 std::mutex compiler error in Visual Studio 2012

后端 未结 3 597
说谎
说谎 2021-01-14 05:57

This a quest about deadlock in C++11 standard.

In the sec3.2.4 of C++ Concurrency in Action, there is an example for preventing multithreads from deadlock. For guys

相关标签:
3条回答
  • 2021-01-14 06:24

    From this reference:

    The mutex class is non-copyable.

    A mutex can't be copied or moved.

    0 讨论(0)
  • 2021-01-14 06:35

    mutexes are not copyable or assignable, and the std::thread constructor is attempting to make a copy. You can circumvent this by using an std::reference_wrapper via std::ref:

    std::thread t1(transfer, std::ref(my_account), std::ref(your_account));
    

    alternatively, you can pass temporary bank_accounts:

    std::thread t1(transfer, bank_account(), bank_account());
    

    This will most likely result in the bank_accounts being "moved" rather than copied, although it is also possible that the copy will be avoided via copy elision.

    0 讨论(0)
  • 2021-01-14 06:38

    You are making copy of my_account and your_account to std::thread, but std::mutex is neither copyable nor movable.

    Try pass by reference:

     std::thread t1(transfer, std::ref(my_account), std::ref(your_account));
    
    0 讨论(0)
提交回复
热议问题