wait_queue.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. MODULE_LICENSE("GPL");
  22. static struct task_struct *kthread1, *kthread2;
  23. static wait_queue_head_t queue;
  24. static atomic_t awake = ATOMIC_INIT(0);
  25. static int kthread_func1(void *data)
  26. {
  27. unsigned int i = 0;
  28. while (!kthread_should_stop()) {
  29. pr_info("1 %u\n", i);
  30. usleep_range(1000000, 1000001);
  31. atomic_set(&awake, 1);
  32. wake_up(&queue);
  33. i++;
  34. }
  35. return 0;
  36. }
  37. static int kthread_func2(void *data)
  38. {
  39. unsigned int i = 0;
  40. while (!kthread_should_stop()) {
  41. pr_info("2 %u\n", i);
  42. i++;
  43. wait_event(queue, atomic_read(&awake));
  44. atomic_set(&awake, 0);
  45. schedule();
  46. }
  47. return 0;
  48. }
  49. static int myinit(void)
  50. {
  51. init_waitqueue_head(&queue);
  52. kthread1 = kthread_create(kthread_func1, NULL, "mykthread1");
  53. kthread2 = kthread_create(kthread_func2, NULL, "mykthread2");
  54. wake_up_process(kthread1);
  55. wake_up_process(kthread2);
  56. return 0;
  57. }
  58. static void myexit(void)
  59. {
  60. /* 2 must be stopped before, or else we can deadlock. */
  61. kthread_stop(kthread2);
  62. kthread_stop(kthread1);
  63. }
  64. module_init(myinit)
  65. module_exit(myexit)