I am learning how to use std::thread
in standard C++, and I can't solve one problem with std::mutex
.
I am running 2 threads with simple functions that show a message in CMD. I want to use a std::mutex
, so that one thread will wait until the other threat stops using the buffer.
When I use the functions everything works fine, but with the functors I have a problem:
error C2280: 'std::mutex::mutex(const std::mutex &)' : attempting to reference a deleted function
What am I doing wrong?
#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)));
}