【问题标题】:Multithreading Timer and I/O in Console C++控制台 C++ 中的多线程计时器和 I/O
【发布时间】:2016-03-14 00:48:15
【问题描述】:

我正在开发一款游戏,其中有一个单词落在屏幕底部,并且用户在该单词到达底部之前输入了该单词。因此,您将能够在单词下降时输入输入。现在我有一个等待 5 秒的计时器,打印单词,再次运行计时器,清除屏幕,然后将单词打印 10 个单位。

int main()
{
  for (int i = 0; i < 6; i++)
   {
    movexy(x, y);
    cout << "hello\n";
    y = y + 10;
    wordTimer();
   }
}

我知道的很基本。这就是为什么我认为多线程是一个好主意,这样我就可以在我仍然在底部输入输入的同时让单词落下。到目前为止,这是我的尝试:

vector<std::thread> threads;

for (int i = 0; i < 5; ++i) {
    threads.push_back(std::thread(task1, "hello\n"));
    threads.push_back(std::thread(wordTimer));
}

for (auto& thread : threads) {
    thread.join();
}

但是,这只会在屏幕上打印 4 次 hello,然后打印 55,然后再次打印 hello,然后再倒计时 3 次。那么有关如何正确执行此操作的任何建议?我已经研究过了。我检查的一些链接没有帮助:

Multithreaded console I/O

C++11 Multithreading: Display to console

Render Buffer on Screen in Windows

Threading console application in c++

Create new console from console app? C++

Console output from thread

https://msdn.microsoft.com/en-us/library/975t8ks0.aspx?f=255&MSPPError=-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;
}

wordTimer() 也需要这个

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;
}

and void 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
        );
}

【问题讨论】:

  • 什么是task1?那是wordtimer?请发布一个包含您的问题的代码示例,我们可以自己编译。
  • @Marinos_K 抱歉 >.
  • " 这只会在屏幕上打印 hello 4 次,然后打印 55,然后再次打印 hello,然后再倒计时 3 次。" - 你期待它做什么?
  • @immibis 不,我希望它先打印 hello 然后倒计时,打印 hello 然后倒计时,等等。我希望它以该顺序运行这些线程,同时让另一个线程连续运行以检查输入是否为等于您输入的字符串。
  • @immibis 感谢您的快速回复!

标签: c++ multithreading timer io


【解决方案1】:

线程不按任何特定顺序运行 - 操作系统可以随时安排它们。您的代码启动了十个线程——五个打印“Hello”,五个倒计时。所以最可能的结果是您的程序将尝试同时打印“Hello”五次,并且同时倒计时五次。 p>

如果您想按特定顺序执行操作,请不要在单独的线程中执行所有操作。只需有一个线程以正确的顺序执行操作即可。

【讨论】:

  • 这确实很有意义!所以你介意告诉我有没有办法让一个字符串落到屏幕底部而不改变光标位置?就像把那根落下的弦当作精灵一样?
  • @user2073308 我以为我已经说过我不知道。 (这里我只是发布了我在我的 cmets 中所说的话,但作为一个答案,看起来它实际上是一个答案)
  • 感谢您的帮助!我现在对线程有了更多的了解。我去别处看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2023-03-17
  • 2011-08-21
  • 2012-06-02
相关资源
最近更新 更多