wait_queue.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. "wait_event" works a bit like:
  3. while (!cond)
  4. sleep_until_event
  5. Outcome:
  6. 1 0
  7. 2 0
  8. # Wait one second.
  9. 1 1
  10. 2 1
  11. # Wait one second.
  12. 1 2
  13. 2 2
  14. # ...
  15. */
  16. #include <linux/delay.h> /* usleep_range */
  17. #include <linux/kernel.h>
  18. #include <linux/kthread.h>
  19. #include <linux/module.h>
  20. #include <linux/wait.h> /* wait_queue_head_t, wait_event_interruptible, wake_up_interruptible */
  21. static struct task_struct *kthread1, *kthread2;
  22. static wait_queue_head_t queue;
  23. static atomic_t awake = ATOMIC_INIT(0);
  24. static int kthread_func1(void *data)
  25. {
  26. unsigned int i = 0;
  27. while (!kthread_should_stop()) {
  28. pr_info("1 %u\n", i);
  29. usleep_range(1000000, 1000001);
  30. atomic_set(&awake, 1);
  31. wake_up(&queue);
  32. i++;
  33. }
  34. return 0;
  35. }
  36. static int kthread_func2(void *data)
  37. {
  38. unsigned int i = 0;
  39. while (!kthread_should_stop()) {
  40. pr_info("2 %u\n", i);
  41. i++;
  42. wait_event(queue, atomic_read(&awake));
  43. atomic_set(&awake, 0);
  44. schedule();
  45. }
  46. return 0;
  47. }
  48. static int myinit(void)
  49. {
  50. init_waitqueue_head(&queue);
  51. kthread1 = kthread_create(kthread_func1, NULL, "mykthread1");
  52. kthread2 = kthread_create(kthread_func2, NULL, "mykthread2");
  53. wake_up_process(kthread1);
  54. wake_up_process(kthread2);
  55. return 0;
  56. }
  57. static void myexit(void)
  58. {
  59. /* 2 must be stopped before, or else we can deadlock. */
  60. kthread_stop(kthread2);
  61. kthread_stop(kthread1);
  62. }
  63. module_init(myinit)
  64. module_exit(myexit)
  65. MODULE_LICENSE("GPL");