Passing a mutex reference to a thread causes compile errors. Why is it not possible (I have multiple threads using the same shared variable), and how do I fix it?
#include<iostream>
#include<thread>
#include<mutex>
void myf(std::mutex& mtx)
{
while(true)
{
// lock
// do something
// unlock
}
}
int main(int argc, char** argv)
{
std::mutex mtx;
std::thread t(myf, mtx);
t.join();
return 0;
}
thread
copies its arguments:
First the constructor copies/moves all arguments...
std::mutex
is not copyable, hence the errors. If you want to pass it by reference, you need to use std::ref
:
std::thread t(myf, std::ref(mtx));
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With