kthread.c 977 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. Kernel threads are managed exactly like userland threads.
  3. They also have a backing task_struct, and are scheduled with the same mechanism.
  4. See also:
  5. - http://stackoverflow.com/questions/10177641/proper-way-of-handling-threads-in-kernel
  6. - http://stackoverflow.com/questions/4084708/how-to-wait-for-a-linux-kernel-thread-kthreadto-exit
  7. */
  8. #include <linux/delay.h> /* usleep_range */
  9. #include <linux/kernel.h>
  10. #include <linux/kthread.h>
  11. #include <linux/module.h>
  12. MODULE_LICENSE("GPL");
  13. static struct task_struct *kthread;
  14. static int work_func(void *data)
  15. {
  16. int i = 0;
  17. while (!kthread_should_stop()) {
  18. printk(KERN_INFO "%d\n", i);
  19. usleep_range(1000000, 1000001);
  20. i++;
  21. if (i == 10)
  22. i = 0;
  23. }
  24. return 0;
  25. }
  26. static int myinit(void)
  27. {
  28. kthread = kthread_create(work_func, NULL, "mykthread");
  29. wake_up_process(kthread);
  30. return 0;
  31. }
  32. static void myexit(void)
  33. {
  34. /* Waits for thread to return. */
  35. kthread_stop(kthread);
  36. }
  37. module_init(myinit)
  38. module_exit(myexit)