wait_queue.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. TODO get working. Thread 2 only wakes up once! Wake thread 2 up every 2 seconds from thread 1.
  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. MODULE_LICENSE("GPL");
  10. static struct task_struct *kthread1, *kthread2;
  11. static wait_queue_head_t queue;
  12. static int awake = 0;
  13. static int kthread_func1(void *data)
  14. {
  15. int i = 0;
  16. while (!kthread_should_stop()) {
  17. awake = !awake;
  18. pr_info("1 %d\n", i);
  19. wake_up_interruptible(&queue);
  20. schedule();
  21. usleep_range(1000000, 1000001);
  22. i++;
  23. if (i == 10)
  24. i = 0;
  25. }
  26. i = !i;
  27. wake_up_interruptible(&queue);
  28. return 0;
  29. }
  30. static int kthread_func2(void *data)
  31. {
  32. set_current_state(TASK_INTERRUPTIBLE);
  33. int i = 0;
  34. while (!kthread_should_stop()) {
  35. wait_event(queue, awake);
  36. pr_info("2 %d\n", i);
  37. set_current_state(TASK_INTERRUPTIBLE);
  38. schedule();
  39. i++;
  40. if (i == 10)
  41. i = 0;
  42. }
  43. return 0;
  44. }
  45. int init_module(void)
  46. {
  47. init_waitqueue_head(&queue);
  48. kthread1 = kthread_create(kthread_func1, NULL, "mykthread1");
  49. kthread2 = kthread_create(kthread_func2, NULL, "mykthread2");
  50. wake_up_process(kthread1);
  51. wake_up_process(kthread2);
  52. return 0;
  53. }
  54. void cleanup_module(void)
  55. {
  56. kthread_stop(kthread1);
  57. kthread_stop(kthread2);
  58. }