diff options
author | crupest <crupest@outlook.com> | 2021-06-07 23:24:43 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2021-06-07 23:24:43 +0800 |
commit | 2dd9b0e926ed97b64f0e6c2b6c071feaab9c47a0 (patch) | |
tree | 6a87c790fc03e3e95f14de9a59257aec66ba65b7 /computer-network-experiment/IO.cpp | |
parent | 1dd5c424e198a59b3572352fd973fe34dad225d1 (diff) | |
download | life-2dd9b0e926ed97b64f0e6c2b6c071feaab9c47a0.tar.gz life-2dd9b0e926ed97b64f0e6c2b6c071feaab9c47a0.tar.bz2 life-2dd9b0e926ed97b64f0e6c2b6c071feaab9c47a0.zip |
...
Diffstat (limited to 'computer-network-experiment/IO.cpp')
-rw-r--r-- | computer-network-experiment/IO.cpp | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/computer-network-experiment/IO.cpp b/computer-network-experiment/IO.cpp new file mode 100644 index 0000000..0c20537 --- /dev/null +++ b/computer-network-experiment/IO.cpp @@ -0,0 +1,80 @@ +#include "IO.h"
+
+#include <folly/CancellationToken.h>
+
+#include <mutex>
+#include <ostream>
+#include <thread>
+#include <type_traits>
+
+folly::MPMCQueue<Output> output_queue(100);
+
+folly::CancellationSource cancellation_source;
+
+std::thread io_thread;
+
+void PrintOutput(const Output &output) {
+ std::basic_ostream<Char> *stream;
+
+ switch (output.type) {
+ case OutputType::Error:
+ stream = &error_stream;
+ break;
+ default:
+ stream = &output_stream;
+ break;
+ }
+
+ switch (output.color) {
+ case OutputColor::Normal:
+ (*stream) << output.message;
+ break;
+ case OutputColor::Green:
+ (*stream) << CRUT("\x1b[32m") << output.message << CRUT("\x1b[39m")
+ << std::flush;
+ break;
+ case OutputColor::Red:
+ (*stream) << CRUT("\x1b[31m") << output.message << CRUT("\x1b[39m")
+ << std::flush;
+ break;
+ case OutputColor::Yellow:
+ (*stream) << CRUT("\x1b[33m") << output.message << CRUT("\x1b[39m")
+ << std::flush;
+ break;
+ }
+}
+
+String ReadInputLine() {
+ String line;
+ std::getline(input_stream, line);
+ return line;
+}
+
+void IOThread() {
+ while (true) {
+ if (cancellation_source.isCancellationRequested()) {
+ while (true) {
+ Output output;
+ if (output_queue.readIfNotEmpty(output)) {
+ PrintOutput(output);
+ } else {
+ return;
+ }
+ }
+ }
+
+ Output output;
+ while (output_queue.readIfNotEmpty(output))
+ PrintOutput(output);
+
+ PrintOutput({CRUT("> ")});
+ OnInputLine(ReadInputLine());
+ }
+}
+
+void SignalAndWaitForOutputThreadStop() {
+ cancellation_source.requestCancellation();
+ io_thread.join();
+}
+
+void StartIOThread() { io_thread = std::thread(IOThread); }
|