using std::cout in multiple threads

前端 未结 4 1897
刺人心
刺人心 2020-12-30 03:58

I write a simple program for testing Thread in c++11 but std::cout doesnt work as I expect.

class Printer
{
public:
    void exec()
    {
               


        
4条回答
  •  失恋的感觉
    2020-12-30 04:41

    The accepted answer is correct. However it is nice to separate concerns:

    1. You need a way to print to std::cout in a thread safe manner.
    2. You need to create objects/functors/functions to run in threads and launch them.

    Here is a utility I use that just concentrates on collecting arguments to std::cout and streaming them out under a static std::mutex:

    #include 
    #include 
    
    std::ostream&
    print_one(std::ostream& os)
    {
        return os;
    }
    
    template 
    std::ostream&
    print_one(std::ostream& os, const A0& a0, const Args& ...args)
    {
        os << a0;
        return print_one(os, args...);
    }
    
    template 
    std::ostream&
    print(std::ostream& os, const Args& ...args)
    {
        return print_one(os, args...);
    }
    
    std::mutex&
    get_cout_mutex()
    {
        static std::mutex m;
        return m;
    }
    
    template 
    std::ostream&
    print(const Args& ...args)
    {
        std::lock_guard _(get_cout_mutex());
        return print(std::cout, args...);
    }
    

    This code can be reused for streams other than std::cout, but the above is specialized to just target std::cout. With this your Printer::exec() can now be significantly simplified:

    void exec()
    {
        print("Hello ", std::this_thread::get_id(), '\n');
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    

    Now, not only will your Printer use cout in a threadsafe manner, and has been simplified (e.g. doesn't need to maintain its own mutex for cout), but all of your other types and functions can also use cout and all interoperate together safely. The print function itself now maintains the mutex, and that fact is encapsulated away from all of print's clients.

提交回复
热议问题