Synchronizing STD cout output multi-thread

前端 未结 5 1189
梦毁少年i
梦毁少年i 2020-12-15 10:21

Latelly I\'ve been working with multi-thread coding, after a while writing I realized that if I used std::cout in different boost::threads, the output would came without a l

5条回答
  •  余生分开走
    2020-12-15 10:57

    Use locking. If you can use boost, do e.g.

    int my01(boost::mutex *coutGuard)
    {
      {
         // lock cout until the closing brace
         boost::mutex::scoped_lock lock(*coutGuard);
    
         std::cout << "my01" << std::endl;
      }
    
      return 0;
    }
    
    int main( void )
    {
       boost::mutex coutGuard;
    
       boost::thread t1(boost::bind(&my01, &coutGuard));
       ...
    }
    

    Instead of a scoped_lock, lock_guard may be used.

提交回复
热议问题