I am studying about threads in C++11 now, and I met the following line of code:
lock_guard<mutex> lg(mutex);
There is no variable mutex. mutex is only name of type.
Can anyone explain me how above line of code works?
Why compiler(GCC) doesn't print any error?
Complete code:
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
void do_something()
{
lock_guard<mutex> lg(mutex);
cout << "Working..." << endl;
this_thread::sleep_for(chrono::milliseconds(3000));
}
int main()
{
thread thd(do_something);
thd.join();
}
The compiler thinks this is a prototype function declaration:
lock_guard<mutex> lg(mutex);
To be clear, the compiler parses this as the declaration of a function named 'lg' which takes a mutex as a parameter and returns a lock_guard instance.
#include <mutex>
int main()
{
using namespace std;
lock_guard<mutex> lg(mutex);
return 0;
}
vc12 output : warning C4930 : 'std::lock_guard<std::mutex> lg(std::mutex)' : prototyped function not called(was a variable definition intended ? )
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