example_spinlock.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * example_spinlock.c
  3. */
  4. #include <linux/init.h>
  5. #include <linux/module.h>
  6. #include <linux/printk.h>
  7. #include <linux/spinlock.h>
  8. static DEFINE_SPINLOCK(sl_static);
  9. static spinlock_t sl_dynamic;
  10. static void example_spinlock_static(void)
  11. {
  12. unsigned long flags;
  13. spin_lock_irqsave(&sl_static, flags);
  14. pr_info("Locked static spinlock\n");
  15. /* Do something or other safely. Because this uses 100% CPU time, this
  16. * code should take no more than a few milliseconds to run.
  17. */
  18. spin_unlock_irqrestore(&sl_static, flags);
  19. pr_info("Unlocked static spinlock\n");
  20. }
  21. static void example_spinlock_dynamic(void)
  22. {
  23. unsigned long flags;
  24. spin_lock_init(&sl_dynamic);
  25. spin_lock_irqsave(&sl_dynamic, flags);
  26. pr_info("Locked dynamic spinlock\n");
  27. /* Do something or other safely. Because this uses 100% CPU time, this
  28. * code should take no more than a few milliseconds to run.
  29. */
  30. spin_unlock_irqrestore(&sl_dynamic, flags);
  31. pr_info("Unlocked dynamic spinlock\n");
  32. }
  33. static int __init 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 __exit 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_DESCRIPTION("Spinlock example");
  47. MODULE_LICENSE("GPL");