msleep() 与 mdelay()


msleep() 与 mdelay()


在Linux Driver开发中,经常要用到延迟函数:msleep,mdelay/udelay.
虽然msleep和mdelay都有延迟的作用,但他们是有区别的.
mdelay是忙等待函数,在延迟过程中无法运行其他任务.这个延迟的时间是准确的.是需要等待多少时间就会真正等待多少时间.而msleep是休眠函数,它不涉及忙等待.你如果是msleep(10),那实际上延迟的时间,大部分时候是要多于10ms的,是个不定的时间值.
他们的差异,平时我也讲的出来,可是真正用起来的时候,就忘记了.曾在两个driver的i2c的code中,需要用到delay函数,而我用了msleep函数,一直I2C速度超慢.而我又不知道哪里出了问题,我潜意识中,认为我只delay了1ms,可是,实际上是十几毫秒.

内核延时

一内核延时函数: 

1.短延时:                        

void ndelay(unsignedlong nsecs);

Void udelay(unsigned long usecs);

Void mdelay(unsigned long msecs);

         前面三个函数都属于忙等延时,对于毫秒级以上的延时,内核提供了下面三个函数(可睡眠):

                                               Voidmsleep(unsigned int msecs);

                                               Unsignedlong msleep_interruptble(unsigned int msecs);//可被打断

                                               Voidssleep(unsigned int second);

2.长延时:

最直观的方法就是比较当前jiffies和目标jiffies(设置为当前jiffies加上时间间隔的jiffies)

         例:(注:这也是忙等)

                  Unsigned long delay = jiffies + 100;

                   While(time_before(jiffies,dealy));//将两个时间进行比较

                            注:Hz相当于1秒。

                   内核中还定义了time_after();

                            #define  time_before(a, b) time_after(b, a);

 

3.睡眠延时:

Schedule_timeout_uninterruptible(jiffies);

Schedule_timeout_interruptible(jiffies);

下面两个函数是将当前进程添加到等待队列中,从而再等待队列上睡眠,当超时发生时,进程将被唤醒:

                   Sleep_on_timeout(wait_queue_head_t*q, unsigned long timeout);

                   Interruptible_Sleep_on_timeout(wait_queue_head_t*q, unsigned long timeout);


二定时器:


你可能感兴趣的:(c,任务,delay)