Noa*_*oah 7 c++ io time asynchronous
我正在写一个服务器(主要用于Windows,但如果我可以保持多平台,这将很酷)我只是使用一个普通的控制台窗口.但是,我希望服务器能够执行诸如text_to_say_here或kick playername等命令.我怎样才能有异步输入/输出?我已经尝试了普通的printf()和gets_s的一些东西但是这导致了一些非常奇怪的东西.
我的意思是这样的事1
谢谢.
利用C++ 11功能的快速代码(即跨平台)
#include <atomic>
#include <thread>
#include <iostream>
void ReadCin(std::atomic<bool>& run)
{
std::string buffer;
while (run.load())
{
std::cin >> buffer;
if (buffer == "Quit")
{
run.store(false);
}
}
}
int main()
{
std::atomic<bool> run(true);
std::thread cinThread(ReadCin, std::ref(run));
while (run.load())
{
// main loop
}
run.store(false);
cinThread.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试将输入和输出放在单独的线程上。我不太确定你为什么要这样做,但线程应该可以完成这项工作。:)
http://en.wikibooks.org/wiki/C++_Programming/Threading