热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Qt中利用计时器启用或禁用特定功能?-HowtoenableordisablespecificfunctionalityinQtusingatimer?

SayIhaveafunctionwork(),onceitiscalled,Idontwantittobecalledinthenext5seconds.

Say I have a function work(), once it is called, I don't want it to be called in the next 5 seconds. Currently, I have designed some simple codes as:

假设我有一个函数work(),一旦调用它,我不希望它在接下来的5秒内被调用。目前,我设计了一些简单的代码:

connect(timer,SIGNAL(timeout()),this,SLOT(resetflag()));
...
if(!flag)
{
    flag = true;
    work();
    timer.start();
}
...
void resetflag(){
  flag = flase;
}

My question is: 1.) How to make this thread safe? 2.) Is there any simpler and elegant way of doing this?

我的问题是:1。)如何使这个线程安全? 2.)有没有更简单和优雅的方式这样做?

1 个解决方案

#1


1  

it may be simpler to just keep a timestamp of the last time you called the function and update it when work is done:

保持上次调用函数的时间戳并在完成工作时更新它可能更简单:

//field
QElapsedTimer timeSinceLastCall;


//function
if(!timeSinceLastCall.isValid()||timeSinceLastCall.hasExpired(5*1000))
{
    timeSinceLastCall.restart();
    work();
}

however the function won't be thread safe (multiple threads can get into work()), you'll need some other way to exclude them such as:

但是该函数不是线程安全的(多线程可以进入work()),你需要一些其他方法来排除它们,例如:

//field
QElapsedTimer timeSinceLastCall;
QMutex mutex;


//function
{
    QMutexLocker locker(&mutex);
    if(timeSinceLastCall.isValid() && !timeSinceLastCall.hasExpired(5*1000))
        return;
    timeSinceLastCall.restart();
}
work();

推荐阅读
author-avatar
许婉玟秀贤
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有