控制台C++中的多线程定时器和I/O
Multithreading Timer and I/O in Console C++
我正在开发一款游戏,它让一个单词掉到屏幕底部,用户在单词掉到底部之前键入该单词。因此,您可以在单词下落时输入。现在我有一个计时器,它会等待5秒,打印单词,再次运行计时器,清除屏幕,并将单词向下打印10个单位。
int main()
{
for (int i = 0; i < 6; i++)
{
movexy(x, y);
cout << "hellon";
y = y + 10;
wordTimer();
}
}
我知道的很基本。这就是为什么我认为多线程是个好主意,这样我就可以在底部输入时让单词下降。到目前为止,这是我的尝试:
vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.push_back(std::thread(task1, "hellon"));
threads.push_back(std::thread(wordTimer));
}
for (auto& thread : threads) {
thread.join();
}
然而,这只在屏幕上打印了4次hello,然后打印了55次,然后再次打印hello,再倒计时3次。那么,关于如何正确地做到这一点,有什么建议吗?我已经做过研究了。我只查看了几个没有帮助的链接:
多线程控制台I/O
C++11多线程:显示到控制台
Windows 中屏幕上的渲染缓冲区
c++中的线程控制台应用
从控制台应用程序创建新控制台?C++
来自线程的控制台输出
https://msdn.microsoft.com/en-us/library/975t8ks0.aspx?f=255&MSPP错误=-2147217396
http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
编辑:这是wordTimer((
int wordTimer()
{
_timeb start_time;
_timeb current_time;
_ftime_s(&start_time);
int i = 5;
for (; i > 0; i--)
{
cout << i << endl;
current_time = start_time;
while (elapsed_ms(&start_time, ¤t_time) < 1000)
{
_ftime_s(¤t_time);
}
start_time = current_time;
}
cout << " 5 seconds have passed." << endl;
return 0;
}
这对于wordTime((也是必要的
unsigned int elapsed_ms(_timeb* start, _timeb* end)
{
return (end->millitm - start->millitm) + 1000 * (end->time - start->time);
}
和任务1
void task1(string msg)
{
movexy(x, y);
cout << msg;
y = y + 10;
}
和空隙movexy(int x,int y(
void movexy(int column, int line)
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE),
coord
);
}
线程不以任何特定的顺序运行-操作系统可以随时安排它们。您的代码启动十个线程-五个打印"Hello",五个倒计时。因此,最有可能的结果是,您的程序将尝试同时打印五次"Hello">,并同时倒数五次。
如果你想按特定的顺序做事,不要把它们都放在单独的线程中。只要有一个线程按正确的顺序执行即可。
相关文章:
- 全局变量 多读取器 一个写入器多线程安全?
- 工作器/控制器多线程和接口类
- 不完整的多线程光线追踪器花费的时间是预期的两倍
- 了解多线程.试图制作一个素数查找器
- C++事件管理器多线程可靠
- 多线程包装器
- C++中多线程中的读取器和编写器
- 控制台C++中的多线程定时器和I/O
- 我们是否需要每个线程多个io_service用于具有单个接受器的线程 boost::asio 服务器
- 在多线程环境中使用 std::string 时 Clang 的线程清理器警告
- 多线程编写器:使用 cpp 的并发问题
- 如何在更多线程上运行提升 asio 解析器服务
- 在具有动态大小内存池的多线程C/C++中实现内存管理器
- Qt多线程项目-调试器冻结
- 多线程定时器类
- 多线程程序与定时器和信号
- 使用boost::asio定时器进行线程安全工作
- 在多线程程序中使用迭代器循环hash_map
- 多线程无锁应用程序中具有多个迭代器的一个向量
- 如何在 C++ 的多线程环境中实现计时器