QT 自定义系统休眠函数

我们在编写Qt程序的时候,有时候需要进行延时处理,使用时钟等手段又不太理想,又不能像C语言那样,利用for循环来达到延时效果,因此需要自定义的延时函数,看过底层的延时函数后,我们可以仿照它这样编写:

/**
 * @brief 延时函数,单位秒
 * @param secs 时间参数
 */
void pureAlgorithm::my_sleep(unsigned long secs)
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    struct timespec ti;
    ti.tv_sec = tv.tv_sec + secs;
    ti.tv_nsec = (tv.tv_usec * 1000);
    my_thread_sleep(&ti);
}

/**
 * @brief 使线程休眠
 * @param ti 休眠结构体,包含了所需信息
 */
void pureAlgorithm::my_thread_sleep(timespec *ti)
{
    pthread_mutex_t mtx;
    pthread_cond_t cnd;
    pthread_mutex_init(&mtx, 0);
    pthread_cond_init(&cnd, 0);
    pthread_mutex_lock(&mtx);
    (void) pthread_cond_timedwait(&cnd, &mtx, ti);
    pthread_mutex_unlock(&mtx);
    pthread_cond_destroy(&cnd);
    pthread_mutex_destroy(&mtx);
}

这样就完成了,其中ti.tv_nsec是自定义的最小时间单位,如此以上。

注意:调用该函数的线程会进入休眠状态,就是在那一行卡着,如果是主线程那你的程序就会出现卡顿

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值