我正在尝试创建一个将反复执行多次但在每个循环之间暂停的函数。
我曾尝试使用“ 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/