linux内核下等待队列的使用

来源:互联网 发布:淘宝网火车票 编辑:程序博客网 时间:2024/04/26 01:49

1、wait_queue的使用

 需要的头文件#include<linux/wait.h>

typedef struct __wait_queue wait_queue_t;

struct __wait_queue {

unsigned int flags;

#define WQ_FLAG_EXCLUSIVE 0x01

void *private;

wait_queue_func_t func;

struct list_head task_list;

};

struct __wait_queue_head {

spinlock_t lock;

struct list_head task_list;

};

typedef struct __wait_queue_head wait_queue_head_t;

Static wait_queue_head_t waitq

用到的函数:

extern void __init_waitqueue_head(wait_queue_head_t *q, struct lock_class_key *);

#define init_waitqueue_head(q) \

do { \

static struct lock_class_key __key; \

\

__init_waitqueue_head((q), &__key); \

} while (0)

用于初始化一个wait_queue_head_t变量

#define wake_up_interruptible(x) __wake_up(x, TASK_INTERRUPTIBLE, 1, NULL)

#define wake_up(x) __wake_up(x, TASK_NORMAL, 1, NULL)

唤醒waitq里的processes,该操作唤醒所有的processes

用于block的函数:

void interruptible_sleep_on(wait_queue_head_t *q);

void sleep_on(wait_queue_head_t *q);

上面两组中wait_upwait_up_interruptible()的区别是:

如果你是用 interruptible_sleep_on() 来将 process 放到 wait_queue 时,如果有人送一个 signal 给这个 process,那它就会自动从 wait_queue 中醒来。但是如果你是用 sleep_on() 把 process 放到 wq 中的话,那不管你送任何的 signal 给它,它还是不会理你的。除非你是使用 wake_up() 将它叫醒。sleep 有两组。wake_up 也有两组。wake_up_interruptible() 会将 wq 中使用 interruptible_sleep_on() 的 process 叫醒。至于 wake_up() 则是会将 wq 中所有的 process 叫醒。包括使用 interruptible_sleep_on() block的 process

使用sleep的步骤

Static  wait_queue_head_t waitq


init_waitqueue_head&waitq);

wake_up_interruptible(&waitq)

interruptible_sleep_on(&waitq) 

注意:以上函数只能在内核层运行,不能在用户层运行。