wait_queue2.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Two threads waiting on a single event.
  3. */
  4. #include <linux/delay.h> /* usleep_range */
  5. #include <linux/kernel.h>
  6. #include <linux/kthread.h>
  7. #include <linux/module.h>
  8. #include <linux/wait.h> /* wait_queue_head_t, wait_event_interruptible, wake_up_interruptible */
  9. static struct task_struct *kthread_wake;
  10. static struct task_struct *kthread_sleep1;
  11. static struct task_struct *kthread_sleep2;
  12. static wait_queue_head_t queue;
  13. static atomic_t awake1 = ATOMIC_INIT(0);
  14. static atomic_t awake2 = ATOMIC_INIT(0);
  15. static int kthread_wake_func(void *data)
  16. {
  17. unsigned int i = 0;
  18. while (!kthread_should_stop()) {
  19. pr_info("0 %u\n", i);
  20. usleep_range(1000000, 1000001);
  21. atomic_set(&awake1, 1);
  22. atomic_set(&awake2, 1);
  23. wake_up(&queue);
  24. i++;
  25. }
  26. return 0;
  27. }
  28. static int kthread_sleep1_func(void *data)
  29. {
  30. unsigned int i = 0;
  31. while (!kthread_should_stop()) {
  32. pr_info("1 %u\n", i);
  33. i++;
  34. wait_event(queue, atomic_read(&awake1));
  35. atomic_set(&awake1, 0);
  36. schedule();
  37. }
  38. return 0;
  39. }
  40. static int kthread_sleep2_func(void *data)
  41. {
  42. unsigned int i = 0;
  43. while (!kthread_should_stop()) {
  44. pr_info("2 %u\n", i);
  45. i++;
  46. wait_event(queue, atomic_read(&awake2));
  47. atomic_set(&awake2, 0);
  48. schedule();
  49. }
  50. return 0;
  51. }
  52. int init_module(void)
  53. {
  54. init_waitqueue_head(&queue);
  55. kthread_wake = kthread_create(kthread_wake_func, NULL, "wake");
  56. kthread_sleep1 = kthread_create(kthread_sleep1_func, NULL, "sleep1");
  57. kthread_sleep2 = kthread_create(kthread_sleep2_func, NULL, "sleep2");
  58. wake_up_process(kthread_wake);
  59. wake_up_process(kthread_sleep1);
  60. wake_up_process(kthread_sleep2);
  61. return 0;
  62. }
  63. void cleanup_module(void)
  64. {
  65. kthread_stop(kthread_sleep2);
  66. kthread_stop(kthread_sleep1);
  67. kthread_stop(kthread_wake);
  68. }
  69. MODULE_LICENSE("GPL");