1、分配初始化一个wait_queue_t结构,将其加入到对应的等待队列
2、设置进程的状态,将其标记为休眠。 TASK_INTERRUPTIBLE、TASK_UNINTERRUPTIBLE
3、检查休眠等待条件,调用schedule(),让出CPU
例如: <linux/sched.h>
1 static ssize_t xxx_write(struct file *file,const char *buffer,size_t count,loff_t *ppos)
2 {
3 ...
4 DECLARE_WAITQUEUE(wait,current);
5 add_wait_queue(&xxx_wait, &wait); //等待队列wait加入等待队列头中
6
7 ret = count;
8
9 do{
10 avail = device_writable(...);
11 if(avail < 0)
12 __set_current_state(TASK_INNTERRUPTIBLE);
13 if(avail < 0){
14 if(filp->f_flags & O_NONBLOCK) {
15 if(!ret)
16 ret = - EAGAIN;
17 goto out;
18 }
19 schedule();
20 if(signal_pending(current)){
21 if(!ret)
22 ret = - ERESTARTSYS;
23 goto out;
24 }
25 }
26 }while(avail < 0);
27
28 device_write(...);
29
30 out:
31 remove_wait_queue(&xxx_wait, &wait);
32 set_current_state(TASK_RUNNING);
33 return ret;
34 }
例如2
第一个步骤是建立并初始化一个等待队列入口:
DEFINE_WAIT(my_wait);或者 wait_queue_t my_wait; init_wait(&my_wait);
将等待队列入口添加到队列中,并设置进程的状态
void prepare_to_wait(wait_queue_head_t *queue,wait_queue_t *wait,int state);
之后可以调用shcedule().
返回时清理
void finish_wait(wait_queue_head_t *queue,wait_queue_t *wait);