在kernel中,將kthread_create()和wake_up_process()包裝成kthread_run(),也就是調用了kthread_run()之後,該thread會立刻被執行。
#include <linux/init.h> #include <linux/module.h> #include <linux/kthread.h> MODULE_LICENSE("GPL"); static struct task_struct *brook_tsk; static int data; static int kbrook(void *arg); static int kbrook(void *arg) { unsigned int timeout; int *d = (int *) arg; for(;;) { if (kthread_should_stop()) break; printk("%s(): %d\n", __FUNCTION__, (*d)++); do { set_current_state(TASK_INTERRUPTIBLE); timeout = schedule_timeout(10 * HZ); } while(timeout); } printk("break\n"); return 0; } static int __init init_modules(void) { int ret; brook_tsk = kthread_create(kbrook, &data, "brook"); if (IS_ERR(brook_tsk)) { ret = PTR_ERR(brook_tsk); brook_tsk = NULL; goto out; } wake_up_process(brook_tsk); return 0; out: return ret; } static void __exit exit_modules(void) { kthread_stop(brook_tsk); } module_init(init_modules); module_exit(exit_modules);
linux/kthread.h
/** * kthread_run - create and wake a thread. * @threadfn: the function to run until signal_pending(current). * @data: data ptr for @threadfn. * @namefmt: printf-style name for the thread. * * Description: Convenient wrapper for kthread_create() followed by * wake_up_process(). Returns the kthread or ERR_PTR(-ENOMEM). */ #define kthread_run(threadfn, data, namefmt, ...) \ ({ \ struct task_struct *__k \ = kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \ if (!IS_ERR(__k)) \ wake_up_process(__k); \ __k; \ })