example_spinlock.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * example_spinlock.c
  3. */
  4. #include <linux/init.h>
  5. #include <linux/interrupt.h>
  6. #include <linux/kernel.h>
  7. #include <linux/module.h>
  8. #include <linux/spinlock.h>
  9. DEFINE_SPINLOCK(sl_static);
  10. spinlock_t sl_dynamic;
  11. static void example_spinlock_static(void)
  12. {
  13. unsigned long flags;
  14. spin_lock_irqsave(&sl_static, flags);
  15. pr_info("Locked static spinlock\n");
  16. /* Do something or other safely. Because this uses 100% CPU time, this
  17. * code should take no more than a few milliseconds to run.
  18. */
  19. spin_unlock_irqrestore(&sl_static, flags);
  20. pr_info("Unlocked static spinlock\n");
  21. }
  22. static void example_spinlock_dynamic(void)
  23. {
  24. unsigned long flags;
  25. spin_lock_init(&sl_dynamic);
  26. spin_lock_irqsave(&sl_dynamic, flags);
  27. pr_info("Locked dynamic spinlock\n");
  28. /* Do something or other safely. Because this uses 100% CPU time, this
  29. * code should take no more than a few milliseconds to run.
  30. */
  31. spin_unlock_irqrestore(&sl_dynamic, flags);
  32. pr_info("Unlocked dynamic spinlock\n");
  33. }
  34. static int example_spinlock_init(void)
  35. {
  36. pr_info("example spinlock started\n");
  37. example_spinlock_static();
  38. example_spinlock_dynamic();
  39. return 0;
  40. }
  41. static void example_spinlock_exit(void)
  42. {
  43. pr_info("example spinlock exit\n");
  44. }
  45. module_init(example_spinlock_init);
  46. module_exit(example_spinlock_exit);
  47. MODULE_DESCRIPTION("Spinlock example");
  48. MODULE_LICENSE("GPL");