我正在使用Qt开发C ++应用程序,我需要每秒异步运行一个函数。
应用程序是这样工作的:
对于其他功能,我使用了Qt集成的SLOTS和SIGNALS,如下所示:
connect(timer, SIGNAL(timeout()), this, SLOT(updateView()));
timer->start(200);
但是对于这个特定的功能,我只想使用C ++功能,例如线程,互斥量,future,promise和asynch 。
我尝试过这样的事情:
if(cmd == start) {
std::future<void> fn = async(std::launch::async, [](){
// some code here
});
}
这样,每次用户单击 start 时,应用程序都会调用lambda函数。
现在,我希望每秒调用一次该函数,直到用户单击 stop ,同时又避免用户执行其他操作。
有人可以帮助我吗?
答案 0 :(得分:2)
使用std::future
假设您的代码执行了一次,以后就会得到一些结果。所以这不是你的情况。
您要寻找的计时器可以实现为具有无限循环的独立线程,该循环会定期调用您的函子。请查看以下决定:
https://stackoverflow.com/a/30425945/149818
答案 1 :(得分:-1)
单向std::thread
。它用于异步运行另一个功能。一旦启动,它就从您提供的函数返回后完成,因此您必须使用循环来控制它。
为了防止出现竞争情况,我通常使用std::atomic
变量来控制该循环。
如果可以从多个并行线程中调用线程对象,则可以使用互斥锁保护该对象,以防止多个并行访问。
一个示例实现可能如下所示:
class MyParallelJob
{
private:
std::thread* _thread = nullptr;
std::atomic<bool> _threadRunning = false;
public:
void startThread()
{
if(_thread == nullptr) // This condition prevents the thread from being started twice.
{
_threadRunning = true; // Set thread loop condition to true
_thread = new std::thread(parallel, this); // Create thread
}
}
void stopThread()
{
if(_thread != nullptr) // Prevents from stopping an stopped thread
{
_threadRunning = false; // Set thread loop condition to false
_thread.join(); // Wait for thread to finish
delete _thread; // Delete thread
_thread = nullptr; // Set thread pointer to nullptr
}
}
void parallel() // Function valled by thread
{
while(_threadRunning == true) // While thread loop condition variable is true(=> stopThread() not called)...
{
//Asynchronous jobs here. (eg. function call)
sleep(1); // Sleep one second
}
}
}