繁体   English   中英

C ++ Delay For-Loop,无需暂停控制台

[英]C++ Delay For-Loop without pausing Console

我正在尝试创建一个可以反复执行多次但每个周期之间暂停的函数。

我试图使用“睡眠”,但暂停了控制台。 我在网上搜索过,只找到了平时暂停控制台的答案。

码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM