Linux 如何使线程休眠/阻塞纳秒(或至少毫秒)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5803715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:50:27  来源:igfitidea点击:

How to make a thread sleep/block for nanoseconds (or at least milliseconds)?

clinuxpthreadssleep

提问by kingsmasher1

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.

请注意,我不能使用 sleep,因为 sleep 的参数总是以秒为单位。

采纳答案by R.. GitHub STOP HELPING ICE

nanosleepor clock_nanosleepis 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).

nanosleep或者clock_nanosleep是您应该使用的函数(后者允许您指定绝对时间而不是相对时间,并使用单调时钟或其他时钟而不仅仅是实时时钟,如果操作员重置它可能会倒退)。

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.)

但是请注意,就分辨率而言,您很少会比几微秒更好,并且它总是将睡眠持续时间向上取整,而不是向下取整。(无论如何,向下舍入通常是不可能的,因为在大多数机器上,进入和退出内核空间需要超过一微秒。)

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.

另外,如果可能的话,我建议使用阻塞等待事件的调用,而不是在很小的时间间隔内休眠然后轮询。例如,pthread_cond_wait, pthread_cond_timedwait, sem_wait, sem_timedwait, select, read, 等取决于您的线程正在执行什么任务以及它如何与其他线程同步和/或与外部世界通信。

回答by Mihran Hovsepyan

Try usleep(). Yes this wouldn't give you nanosecond precision but microseconds will work => miliseconds too.

试试usleep()。是的,这不会给你纳秒精度,但微秒也可以工作 => 毫秒。

回答by Darhuuk

Accurate nano-second resolution is going to be impossible on a general Linux OS, due to the fact that generally Linux distributions aren't (hard) real-time OSes. If you reallyneed that fined grained control over timing, consider using such an operating system.

在一般的 Linux 操作系统上,准确的纳秒分辨率是不可能的,因为通常 Linux 发行版不是(硬)实时操作系统。如果您真的需要对时间进行细粒度控制,请考虑使用这样的操作系统。

Wikipedia has a list of some real-time operating systems here: http://en.wikipedia.org/wiki/RTOS(note that it doesn't say if they are soft or hard real time, so you'll have to do some research).

维基百科在此处列出了一些实时操作系统:http: //en.wikipedia.org/wiki/RTOS(请注意,它没有说明它们是软实时还是硬实时,因此您必须这样做有些研究)。

回答by Furquan

Using any variant of sleep for pthreads, the behaviour is not guaranteed. All the threads can also sleep since the kernel is not aware of the different threads. Hence a solution is required which the pthread library can handle rather than the kernel.

对 pthread 使用 sleep 的任何变体,都不能保证行为。所有线程也可以休眠,因为内核不知道不同的线程。因此,需要一个 pthread 库而不是内核可以处理的解决方案。

A safer and cleaner solution to use is the pthread_cond_timedwait...

使用更安全、更清洁的解决方案是 pthread_cond_timedwait...

pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;

void mywait(int timeInSec)
{
struct timespec timeToWait;
struct timeval now;
int rt;

gettimeofday(&now,NULL);

timeToWait.tv_sec = now.tv_sec + timeInSec;
timeToWait.tv_nsec = now.tv_usec*1000;

pthread_mutex_lock(&fakeMutex);
rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
pthread_mutex_unlock(&fakeMutex);
printf("\nDone\n");
}

void* fun(void* arg)
{
printf("\nIn thread\n");
mywait(5);
}

int main()
{
pthread_t thread;
void *ret;

pthread_create(&thread, NULL, fun, NULL);
pthread_join(thread,&ret);
}

For pthread_cond_timedwait , you need to specify how much time to wait from current time.

对于 pthread_cond_timedwait ,您需要指定从当前时间开始等待的时间。

Now by the use of the function mywait() only the thread calling it will sleep and not the other pthreads.

现在通过使用函数 mywait() 只有调用它的线程会休眠,而不是其他 pthread。

回答by Douglas Leeder

nanosleepallows you to specify the accuracy of the sleep down to nano-seconds. However the actual resolution of your sleep is likely to be much larger due to the kernel/CPU limitations.

nanosleep允许您将睡眠的精度指定为纳秒级。然而,由于内核/CPU 的限制,您的睡眠的实际分辨率可能要大得多。

回答by Maxim Egorushkin

One relatively portable way is to use select()or pselect()with no file descriptors:

一种相对可移植的方式是使用select()pselect()不使用文件描述符:

void sleep(unsigned long nsec) {
    struct timespec delay = { nsec / 1000000000, nsec % 1000000000 };
    pselect(0, NULL, NULL, NULL, &delay, NULL);
}

回答by R.. GitHub STOP HELPING ICE

On an embedded system with access to multiple hardware timers, create a high-speed clock for your nanosecond or microsecond waits. Create a macro to enable and disable it, and handle your high-resolution processing in the timer interrupt service routine.

在可以访问多个硬件计时器的嵌入式系统上,为纳秒或微秒等待创建一个高速时钟。创建一个宏来启用和禁用它,并在定时器中断服务例程中处理您的高分辨率处理。

If wasting power and busywaiting is not an issue, perform some no-op instructions - but verify that the compiler does not optimize your no-ups out. Try using volatile types.

如果浪费电源和忙等待不是问题,请执行一些无操作指令 - 但请确认编译器没有优化您的无操作指令。尝试使用 volatile 类型。