example_spinlock.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.
  17. Because this uses 100% CPU time this
  18. code should take no more than a few
  19. milliseconds to run */
  20. spin_unlock_irqrestore(&sl_static, flags);
  21. pr_info("Unlocked static spinlock\n");
  22. }
  23. static void example_spinlock_dynamic(void)
  24. {
  25. unsigned long flags;
  26. spin_lock_init(&sl_dynamic);
  27. spin_lock_irqsave(&sl_dynamic, flags);
  28. pr_info("Locked dynamic spinlock\n");
  29. /* Do something or other safely.
  30. Because this uses 100% CPU time this
  31. code should take no more than a few
  32. milliseconds to run */
  33. spin_unlock_irqrestore(&sl_dynamic, flags);
  34. pr_info("Unlocked dynamic spinlock\n");
  35. }
  36. static int example_spinlock_init(void)
  37. {
  38. pr_info("example spinlock started\n");
  39. example_spinlock_static();
  40. example_spinlock_dynamic();
  41. return 0;
  42. }
  43. static void example_spinlock_exit(void)
  44. {
  45. pr_info("example spinlock exit\n");
  46. }
  47. module_init(example_spinlock_init);
  48. module_exit(example_spinlock_exit);
  49. MODULE_DESCRIPTION("Spinlock example");
  50. MODULE_LICENSE("GPL");