如何使线程休眠/阻塞达纳秒(或至少毫秒)? [英] How to make a thread sleep/block for nanoseconds (or at least milliseconds)?

查看:173
本文介绍了如何使线程休眠/阻塞达纳秒(或至少毫秒)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能将线程(可能正在处理)阻塞十亿分之一秒或至少几毫秒?

How can I block my thread (maybe process) for nanoseconds or maybe for a milliseconds (at least) period?

请注意,我不能使用睡眠,因为睡眠参数总是以秒为单位.

Please note that I can't use sleep, because the argument to sleep is always in seconds.

推荐答案

nanosleepclock_nanosleep是您应该使用的函数(后者允许您指定绝对时间而不是相对时间,并使用单调时钟或其他时钟,而不仅仅是实时时钟,如果操作员将其重置,则可能会向后运行.

nanosleep or clock_nanosleep is the function you should be using (the latter allows you to specify absolute time rather than relative time, and use the monotonic clock or other clocks rather than just the realtime clock, which might run backwards if an operator resets it).

但是请注意,就分辨率而言,您很少会获得比几微秒更好的效果,并且它总是使睡眠时间四舍五入,而不是四舍五入. (由于在大多数计算机上,进入和退出内核空间都需要一微秒的时间,因此通常无法进行舍入运算.)

Be aware however that you'll rarely get better than several microseconds in terms of the resolution, and it always rounds up the duration of sleep, rather than rounding down. (Rounding down would generally be impossible anyway since, on most machines, entering and exiting kernelspace takes more than a microsecond.)

此外,如果可能的话,我建议使用阻止事件等待的呼叫,而不是在很小的时间间隔内进行睡眠然后进行轮询.例如,pthread_cond_waitpthread_cond_timedwaitsem_waitsem_timedwaitselectread等,取决于线程正在执行的任务以及与其他线程同步和/或与线程通信的方式.外部世界.

Also, if possible I would suggest using a call that blocks waiting for an event rather than sleeping for tiny intervals then polling. For instance, pthread_cond_wait, pthread_cond_timedwait, sem_wait, sem_timedwait, select, read, etc. depending on what task your thread is performing and how it synchronizes with other threads and/or communicates with the outside world.

这篇关于如何使线程休眠/阻塞达纳秒(或至少毫秒)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆