【问题标题】:Asynchronous timer within a function函数内的异步定时器
【发布时间】:2016-02-21 18:00:43
【问题描述】:

我有一个在 NCurses 界面中从左到右滚动文本的功能,但它依赖于每 500 毫秒左右的计时器来正确写出前面的新字符并删除后面的前一个字符。代码如下:

void GekkoFyre::TuiHangouts::gui_scrollText(WINDOW *display, const char *msg,
                                            const int &msgPosY)
{
    size_t maxX = getmaxx(display);
    size_t msgLen = strlen(msg);
    short origPosY = 0;
    short origPosX = 0;
    getyx(display, origPosY, origPosX); // Obtain the original cursor position

    if (msgLen > maxX) {
        // size_t diff = (msgLen - maxX);
        size_t i = 0;
        for (i = maxX; i < msgLen; ++i) {
            // Scroll the message from left to right, then vice versa, so that it fits within the
            // designated window.
            move(msgPosY, 0);
            clrtoeol(); // Delete just the given line, <http://stackoverflow.com/questions/5072881/how-to-clear-a-specific-line-with-ncurses>
            move(origPosY, origPosX); // Go back to the original cursor position
            std::string tmp((msgLen - i), msg[(msgLen - i)]);
            wattron(display, A_REVERSE); // Highlight selection
            mvwaddstr(display, msgPosY, 0, tmp.c_str());
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    }
}

老实说,我不知道这是否可行,因为我一直无法让它发挥作用。但是有没有像std::this_thread::sleep_for(std::chrono::milliseconds(500)); 这样的计时器,您可以在函数中使用但它是异步的?那将是美丽的!我做了一些研究,遇到了 std::async 和 std::thread,但它们依赖于函数的外部。

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 它可能无论如何都行不通,因为它使用线程(参见FAQ)。

标签: c++ c++11 asynchronous timer ncurses


【解决方案1】:

但是有没有像std::this_thread::sleep_for(std::chrono::milliseconds(500)); 这样的计时器,您可以在函数中使用但它是异步的?

不,你不能。您实际上从异步行为这个术语中得到了什么。您需要在代码的其他地方有一个连接点来捕获计时器已用事件。

【讨论】:

  • 连接点是什么意思?抱歉,但我真的在为编程的命名而苦恼。我从未正式学习过,但完全是自学成才,一路上尽我所能学习,不知道很多其他人“刚刚得到”的术语真的很令人沮丧。
  • @Phobos 好吧,计时器已过的加入点仅仅意味着你需要有一个回调在你的函数之外捕获它。
猜你喜欢
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2021-02-20
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
相关资源
最近更新 更多