相关疑难解决方法(0)

在多个线程中使用std :: cout

我在c ++ 11中编写了一个用于测试Thread的简单程序,但是std::cout没有按照我的预期工作.

class Printer
{
public:
    void exec()
    {
        mutex m;
        m.lock();
        cout<<"Hello  "<<this_thread::get_id()<<endl;
        chrono::milliseconds duration( 100 );
        this_thread::sleep_for( duration );
        m.unlock();

    }
};

int main()
{
    Printer printer;

    thread firstThread([&printer](){
        while(1)
            printer.exec();

    });
    thread secondThread([&printer](){
        while(1)
            printer.exec();
    });

    firstThread.join();
    secondThread.join();     
}
Run Code Online (Sandbox Code Playgroud)

一些结果:

Hello 11376
Hello 16076
Hello 16076
Hello Hello 11376
16076
Hello 11376
,....
Run Code Online (Sandbox Code Playgroud)

我使用互斥锁来锁定线程,所以我无法理解为什么两个线程同时执行std::cout.它接缝非常适合我.任何人都可以解释发生了什么!?!

c++ multithreading mutex c++11 stdthread

15
推荐指数
3
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1

multithreading ×1

mutex ×1

stdthread ×1