example_spinlock.c 1.4 KB

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