I write a simple program for testing Thread in c++11 but std::cout doesnt work as I expect.
class Printer
{
public:
void exec()
{
The threads are using different mutex instances as the mutex is a local variable in the exec() function so locking the mutex is pointless as each thread will be locking its own mutex resulting in no synchronization between the threads. The same mutex instance must be used by the threads to achieve synchronization.
To correct in the posted code, make the mutex a member variable. However, if another Printer object was created then there would be no synchronization between threads that used different Printer instances. In this case, the mutex would need to be a static member variable to ensure synchronization:
class Printer
{
public:
//...
private:
static std::mutex mtx_;
};
std::mutex Printer::mtx_;
To ensure a mutex is always released, regardless if a function exits normally or via an exception, use std:lock_guard:
std::lock_guard lock(m); // 'm' locked, and will be
// unlocked when 'lock' is destroyed.
std::cout<< "Hello " << std::this_thread::get_id() << std::endl;
std::chrono::milliseconds duration( 100 );
std::this_thread::sleep_for( duration );