C ++ 11 std :: mutex compiler error in Visual Studio 2012
This is a quest for a dead end in the C ++ 11 standard.
Section sec.2.2.4 of C ++ Concurrency in Action has an example for preventing multithread blocking. For the guys without this book, in addition, there is another almost similar example you can refer to: http://en.cppreference.com/w/cpp/thread/lock_tag
The problem I am facing is that the codes of both codes appear with compiler errors in Visual Studio 2012. Error message:
'std::mutex::mutex': cannot access private member declared in class 'std::mutex'
This problem also occurs in the following simpler code than cppreference.com:
struct bank_account {
std::mutex m;
};
void transfer(bank_account &from, bank_account &to)
{
std::lock(from.m, to.m);
}
int _tmain(int argc, _TCHAR* argv[])
{
bank_account my_account;
bank_account your_account;
std::thread t1(transfer, my_account, your_account); // compiler-error!
std::system("pause");
return 0;
}
Any idea to resolve this issue in Visual Studio 2012?
source to share
mutexes
cannot be copied or assigned, and the constructor std::thread
tries to make a copy. You can get around this using std::reference_wrapper
via std::ref
:
std::thread t1(transfer, std::ref(my_account), std::ref(your_account));
you can pass temporary bank_accounts
:
std::thread t1(transfer, bank_account(), bank_account());
This will most likely result in being bank_accounts
"moved" rather than copied, although it is also possible that the copy will be removed by copying.
source to share
You make a copy my_account
, and your_account
in the std :: thread , but std :: mutex is neither copied nor mobile.
Try following the link:
std::thread t1(transfer, std::ref(my_account), std::ref(your_account));
source to share