Visual Studio 2012中的c ++ 11 std :: mutex编译器错误 [英] c++11 std::mutex compiler error in Visual Studio 2012

查看:83
本文介绍了Visual Studio 2012中的c ++ 11 std :: mutex编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对C ++ 11标准中的死锁的追求.

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

在C ++并发操作的sec3.2.4中,有一个示例 防止多线程死锁.对于没有这本书的人, 此外,还有另一个几乎相似的示例可以参考: http://en.cppreference.com/w/cpp/thread/lock_tag

In the sec3.2.4 of C++ Concurrency in Action, there is an example for preventing multithreads from deadlock. For guys without this book, in addition, there is an another almost similar example you can refer to: http://en.cppreference.com/w/cpp/thread/lock_tag

我遇到的问题是两个代码的代码都出现了编译器错误 在Visual Studio 2012中.错误消息是:

The problem I encountered is that the codes of both codes arise compiler-errors in Visual Studio 2012. The error message is:

'std::mutex::mutex': cannot access private member declared in class 'std::mutex'

在以下比cppreference.com更简单的代码中也会发生此问题:

This problem also happens in the following simpler code than in 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;
}

有什么想法可以在Visual Studio 2012中解决此问题?

Any idea to solve this problem in Visual Studio 2012?

推荐答案

mutexes是不可复制或不可分配的,并且std::thread构造函数正在尝试进行复制.您可以通过std::ref通过std::reference_wrapper来避免此问题:

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));

或者,您可以传递临时bank_accounts:

alternatively, you can pass temporary bank_accounts:

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

这很可能导致bank_accounts被移动"而不是被复制,尽管也有可能通过 copy Elision 避免了复制.

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.

这篇关于Visual Studio 2012中的c ++ 11 std :: mutex编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆