Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 核心等待佇列 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)

前者只喚醒以 TASK_INTERRUPTIBLE 狀態休眠的行程,後者會把佇列中所有行程全部喚醒。

三、進入睡眠

void interruptible_sleep_on(wait_queue_head_t *q);
void sleep_on(wait_queue_head_t *q);

兩者的差別在於對信號的反應:用 interruptible_sleep_on() 放進佇列的行程,一旦收到 signal 就會自動醒來;而用 sleep_on() 放進去的行程,不管你送什麼信號它都不理,只能被 wake_up() 叫醒。

對應關係整理:

  • wake_up_interruptible() 只叫醒用 interruptible_sleep_on() 進入佇列的行程。
  • wake_up() 叫醒佇列中的所有行程,包含 interruptible_sleep_on() 的那批。

四、使用步驟

static wait_queue_head_t waitq;

init_waitqueue_head(&waitq);
wake_up_interruptible(&waitq);
interruptible_sleep_on(&waitq);

注意:以上函式只能在使用者核心層(kernel space)使用,不可在 user space 呼叫。

實務上新版核心更推薦搭配 wait_event_interruptible() 這類巨集搭配條件判斷使用,可以避免「睡死了卻沒人叫醒」的競態問題。

Copyright © Linux教程網 All Rights Reserved