synchronizing using completion function

essential linux device dirver:

 

In the following example,  'my_release' is called when module is removed.

But before the module's unloaded, you have to make sure that 'my_thread'

has finished some very important task which will incur harmful effective to

our system if not properly handled. When 'my_thread' has finished the critical

task,  call 'complete_and_exit' to signal 'my_release' . In the 'my_releas'  side,

it can call 'wait_for_completion' to wait for 'my_thread' to exit. When 'my_release'

return from 'wait_for_completion' call,  the module can safely unloaded.

 

sample code:

 

#include <linux/module.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/wait.h> static DECLARE_COMPLETION(my_thread_exit); // Completion static DECLARE_WAIT_QUEUE_HEAD(my_thread_wait); // Wait queue int pink_slip = 0; // exit flag for my_thread // Helper thread static int my_thread(void *unused) { DECLARE_WAITQUEUE(wait, current); daemonize("my_thread"); add_wait_queue(&my_thread_wait, &wait); while (1) { // Relinquish processor until event occurs set_current_state(TASK_INTERRUPTIBLE); schedule(); /* Control gets here when the thread is woken up from the my_threa_wait wait queue */ // quit if let go if (pink_slip){ break; } // do the real work } // Here you can do something printk("you can do some important work./n"); printk("Hi, This is %s. I am ready to die./n", __func__); set_current_state(TASK_RUNNING); remove_wait_queue(&my_thread_wait, &wait); // Atomatically signal completion and exit complete_and_exit(&my_thread_exit, 0); } static int __init my_init(void) { printk("Hello, my dear!/n"); // Kick start the thread kernel_thread(my_thread, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND | SIGCHLD); return 0; } static void __exit my_release(void) { printk("Bye, my dear!/n Cruel world!/n"); pink_slip = 1; // set the exit flag of my_thread printk("Hi, I am %s. The module will be unloaded, Please ready!/n", __func__); wake_up(&my_thread_wait); // activate my_thread wait_for_completion(&my_thread_exit);// Wait until my_thread quits } module_init(my_init); module_exit(my_release); MODULE_LICENSE("Dual BSD/GPL");

你可能感兴趣的:(thread,linux,function,Module,System,Signal)