From 92e759a676b5f2886160fc8f43744f137a0a19b1 Mon Sep 17 00:00:00 2001 From: Marco Costalba Date: Wed, 29 Aug 2012 11:25:11 +0200 Subject: [PATCH] Introduce serialization of accesses to std::cout When many threds concurrently print you need to serialize the access to std::cout to avoid output lines are intermixed with the contents of each thread. This is not strictly needed at the moment because only main thread prints out, although some ad-hoc test could trigger UCI::loop() printing while searching. Anyhow we want to lift this pretty avoidable constrain also as a prerequisite for future work. This patch just introduces the support, next one will enable the serialization. No functional change. Signed-off-by: Marco Costalba --- src/misc.cpp | 17 +++++++++++++++++ src/misc.h | 7 +++++++ 2 files changed, 24 insertions(+) diff --git a/src/misc.cpp b/src/misc.cpp index 1a092c61..ababdbc1 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -146,6 +146,23 @@ public: }; +/// Used to serialize access to std::cout to avoid multiple threads to write at +/// the same time. + +std::ostream& operator<<(std::ostream& os, SyncCout sc) { + + static Mutex m; + + if (sc == io_lock) + m.lock(); + + if (sc == io_unlock) + m.unlock(); + + return os; +} + + /// Trampoline helper to avoid moving Logger to misc.h void start_logger(bool b) { Logger::start(b); } diff --git a/src/misc.h b/src/misc.h index 57e86553..24d41d1a 100644 --- a/src/misc.h +++ b/src/misc.h @@ -65,4 +65,11 @@ private: std::vector e; }; + +enum SyncCout { io_lock, io_unlock }; +std::ostream& operator<<(std::ostream&, SyncCout); + +#define sync_cout std::cout << io_lock +#define sync_endl std::endl << io_unlock + #endif // !defined(MISC_H_INCLUDED) -- 2.39.2