工作隊列類似 tasklets,允許內核代碼請求在將來某個時間調用一個函數,不同在於:
(1)tasklet 在軟件中斷上下文中運行,所以 tasklet 代碼必須是原子的。而工作隊列函數在一個特殊內核進程上下文運行,有更多的靈活性,且能夠休眠。
(2)tasklet 只能在最初被提交的處理器上運行,這只是工作隊列默認工作方式。
(3)內核代碼可以請求工作隊列函數被延後一個給定的時間間隔。
(4)tasklet 執行的很快, 短時期, 並且在原子態, 而工作隊列函數可能是長週期且不需要是原子的,兩個機制有它適合的情形。
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <linux/cdev.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
void work_function(unsigned long sign);
static struct work_struct my_work;
void work_function(unsigned long sign)
{
printk(KERN_EMERG"work out %ld\n",sign);
}
static void work_init(void)
{
INIT_WORK(&my_work,(void(*)(void*))work_function,4);
schedule_work(&my_work);
}
static void work_exit(void)
{
printk(KERN_EMERG"GOOBYE,WORLD\t\n");
}
module_init(work_init);
module_exit(work_exit);
MODULE_LICENSE("Dual BSD/GPL");
測試結果如下:
[root@localhost work_queue]# insmod work.ko
[root@localhost work_queue]#
Message from syslogd@ at Mon Aug 13 14:52:36 2012 ...
localhost kernel: work out 4
[root@localhost work_queue]#