我正在学习如何在标准C++中使用std::thread
,并且我无法用std::mutex
解决一个问题。C++如何使用函子使用std :: mutex和std :: lock_guard?
我正在运行2个线程,使用简单的函数在CMD中显示一条消息。我想使用std::mutex
,以便一个线程将等待,直到其他威胁停止使用缓冲区。
当我使用功能一切正常,但与仿函数我有一个问题:
错误C2280: '的std ::互斥::互斥(常量的std ::互斥&)':尝试以引用删除的功能
我在做什么错?
#include <iostream>
#include <thread>
#include <mutex>
class thread_guard
{
private:
std::thread m_thread;
public:
thread_guard(std::thread t)
{
m_thread = std::move(t);
if (!m_thread.joinable())
std::cout << "Brak watku!!!" << std::endl;
}
~thread_guard()
{
m_thread.join();
}
};
class func
{
private:
std::mutex mut;
public:
void operator()()
{
for (int i = 0; i < 11000; i++)
{
std::lock_guard<std::mutex> guard(mut);
std::cout << "watek dziala 1" << std::endl;
}
}
};
class func2
{
private:
std::mutex mut;
public:
void operator()()
{
for (int i = 0; i < 11000; i++)
{
std::lock_guard<std::mutex> guard(mut);
std::cout << "watek dziala 2" << std::endl;
}
}
};
std::mutex mut2;
void fun()
{
for (int i = 0; i < 11000; i++)
{
std::lock_guard<std::mutex> guard(mut2);
std::cout << "watek dziala 1" << std::endl;
}
}
void fun2()
{
for (int i = 0; i < 11000; i++)
{
std::lock_guard<std::mutex> guard(mut2);
std::cout << "watek dziala 2" << std::endl;
}
}
int main(void)
{
thread_guard t1((std::thread(func())));
thread_guard t2((std::thread(func2())));
//thread_guard t1((std::thread(fun)));
//thread_guard t2((std::thread(fun2)));
}
见本:http://stackoverflow.com/questions/21409439/error-c2280-attempting-to- reference-a-deleted-function – hauron 2014-08-27 08:23:18
错误指出您正试图复制互斥锁(调用复制构造函数),显然这是不允许的。 – stefaanv 2014-08-27 08:25:13
但我做功能一样,但在课堂上。那么问题在哪里? – user3808229 2014-08-27 08:34:26