C++ 在不暂停控制台的情况下延迟 For-Loop

标签 c++

我正在尝试创建一个将反复执行多次但在每个循环之间暂停的函数。

我曾尝试使用“ sleep ”,但这会暂停控制台。我在网上搜索过,只找到了平时暂停控制台的答案。

代码:

int i;
for(i=0; i<500; i++) {
    std::cout << "Hello" << std::endl;
}

如何让它打印“Hello”500 次,并允许用户在执行上述功能时使用控制台?

最佳答案

正如一些人评论的那样,您需要创建一个异步任务,以便在处理用户输入的同时完成一些工作。

以下是关于如何使用线程完成此任务的最小工作示例。它基于 boost,因此您必须使用 -lboost_thread lboost_system 链接它:

g++ test.cpp -lboost_thread -lboost_system -o test 

代码有几条注释以解释您应该做什么:

#include <queue>
#include <iostream>
#include <boost/thread.hpp>

// set by the main thread when the user enters 'quit'
bool stop = false;
boost::mutex stopMutex; // protect the flag!


// the function that runs in a new thread
void thread_function() {
    // the following is based on the snippet you wrote
    int i;
    for(i=0; i<500; i++) {
        // test if I have to stop on each loop
        {
            boost::mutex::scoped_lock lock(stopMutex);
            if (stop) {
                break;
            }
        }

        // your task
        std::cout << "Hello" << std::endl;

        // sleep a little
        ::usleep(1000000);
    }
}


int main() {
    std::string str;
    boost::thread t(thread_function);

    while(true) {
        std::cout << "Type 'quit' to exit: ";

        // will read user input
        std::getline(std::cin, str);

        if (str == "quit") {
            // the user wants to quit the program, set the flag
            boost::mutex::scoped_lock lock(stopMutex);
            stop = true;
            break;
        }
    }

    // wait for the async task to finish
    t.join();

    return 0;
}

关于C++ 在不暂停控制台的情况下延迟 For-Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44209443/

相关文章:

c++ - QPushButton 中的两种颜色文本

.net - C++ 'GET' 请求或如何下载文件以在 C++ 中使用?

java - 使用 NewGlobalRef 时的 JNI "local reference table overflow"

c++ - 如何使用 cytpes 将 int 列表的列表从 python 传递给 C++ 函数

c++ - Boost::MSM:转换优先级

c++ - 如何将值插入结构中的 vector

c++ - C++ 中的 memcpy 等价物是什么

c++ - 嵌套的 openmp 导致段错误(仅限 MacOS X)

c++ - 通用模板模板参数

c++ - 是否为这个重载运算符调用了转换构造函数? (C++)