kthread.c 967 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. static struct task_struct *kthread;
  13. static int work_func(void *data)
  14. {
  15. int i = 0;
  16. while (!kthread_should_stop()) {
  17. pr_info("%d\n", i);
  18. usleep_range(1000000, 1000001);
  19. i++;
  20. if (i == 10)
  21. i = 0;
  22. }
  23. return 0;
  24. }
  25. static int myinit(void)
  26. {
  27. kthread = kthread_create(work_func, NULL, "mykthread");
  28. wake_up_process(kthread);
  29. return 0;
  30. }
  31. static void myexit(void)
  32. {
  33. /* Waits for thread to return. */
  34. kthread_stop(kthread);
  35. }
  36. module_init(myinit)
  37. module_exit(myexit)
  38. MODULE_LICENSE("GPL");