控制台C++中的多线程定时器和I/O

Multithreading Timer and I/O in Console C++

本文关键字:定时器 多线程 C++ 控制台      更新时间:2023-10-16

我正在开发一款游戏,它让一个单词掉到屏幕底部,用户在单词掉到底部之前键入该单词。因此,您可以在单词下落时输入。现在我有一个计时器,它会等待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, &current_time) < 1000)
        {
            _ftime_s(&current_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">,并同时倒数五次

如果你想按特定的顺序做事,不要把它们都放在单独的线程中。只要有一个线程按正确的顺序执行即可。