在linux核心态下sleep

在Linux驱动程序中,若不想使用udelay()或mdelay()这种忙等待函数(会浪费CPU时间且可能关中断),可使用schedule_timeout(seconds*HZ)或interruptible_sleep_on_timeout(q,seconds*HZ)。前者简单直接,时间到仅变为就绪;后者繁琐需定义等待队列,但时间到一定唤醒。
有的时候,需要在驱动程序中小睡一会,又不想使用udelay()或者是mdelay()这种忙等待(因为他们会浪费CPU时间,更重要的是,印象中会关中断--帮我确认一下),那么最好使用schedule_timeout(seconds*HZ)这个函数,或者用interruptible_sleep_on_timeout(q,seconds*HZ)来做。前者比较简单直接,后者使用起来比较繁琐,还要定义等待队列;但是后者的好处在于时间到了一定唤醒,而前者时间到了仅仅变为就绪,还要等待CPU调度。
Linux下,sleep函数用于暂停程序的执行一段时间。它的参数是以秒为单位的延迟时间。例如,sleep(1)表示延迟1秒。\[1\]\[2\]在C语言中,可以使用sleep函数来实现延迟效果。例如,下面的代码会先输出"hello",然后延迟1秒,最后输出"world": #include <stdio.h> #include <unistd.h> int main() { printf("hello\n"); sleep(1); printf("world\n"); return 0; } 在这个例子中,程序会先输出"hello",然后调用sleep函数延迟1秒,最后输出"world"。sleep函数会暂停程序的执行,直到指定的延迟时间过去为止。\[2\] 另外,如果你想立即将输出显示在屏幕上,可以使用fflush函数刷新缓存。例如,下面的代码会先输出"hello",然后立即将输出显示在屏幕上,再延迟1秒,最后输出"world": #include <stdio.h> #include <unistd.h> int main() { printf("hello"); fflush(stdout); sleep(1); printf("world\n"); return 0; } 通过调用fflush(stdout)函数,可以强制刷新缓存,使得输出立即显示在屏幕上。\[3\] #### 引用[.reference_title] - *1* *2* *3* [Linux下的延迟函数sleep()](https://blog.youkuaiyun.com/nigulasi_dawei/article/details/72865390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值