1
0

example_atomic.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * example_atomic.c
  3. */
  4. #include <linux/atomic.h>
  5. #include <linux/bitops.h>
  6. #include <linux/module.h>
  7. #include <linux/printk.h>
  8. #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
  9. #define BYTE_TO_BINARY(byte) \
  10. ((byte & 0x80) ? '1' : '0'), ((byte & 0x40) ? '1' : '0'), \
  11. ((byte & 0x20) ? '1' : '0'), ((byte & 0x10) ? '1' : '0'), \
  12. ((byte & 0x08) ? '1' : '0'), ((byte & 0x04) ? '1' : '0'), \
  13. ((byte & 0x02) ? '1' : '0'), ((byte & 0x01) ? '1' : '0')
  14. static void atomic_add_subtract(void)
  15. {
  16. atomic_t debbie;
  17. atomic_t chris = ATOMIC_INIT(50);
  18. atomic_set(&debbie, 45);
  19. /* subtract one */
  20. atomic_dec(&debbie);
  21. atomic_add(7, &debbie);
  22. /* add one */
  23. atomic_inc(&debbie);
  24. pr_info("chris: %d, debbie: %d\n", atomic_read(&chris),
  25. atomic_read(&debbie));
  26. }
  27. static void atomic_bitwise(void)
  28. {
  29. unsigned long word = 0;
  30. pr_info("Bits 0: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  31. set_bit(3, &word);
  32. set_bit(5, &word);
  33. pr_info("Bits 1: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  34. clear_bit(5, &word);
  35. pr_info("Bits 2: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  36. change_bit(3, &word);
  37. pr_info("Bits 3: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  38. if (test_and_set_bit(3, &word))
  39. pr_info("wrong\n");
  40. pr_info("Bits 4: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  41. word = 255;
  42. pr_info("Bits 5: " BYTE_TO_BINARY_PATTERN "\n", BYTE_TO_BINARY(word));
  43. }
  44. static int __init example_atomic_init(void)
  45. {
  46. pr_info("example_atomic started\n");
  47. atomic_add_subtract();
  48. atomic_bitwise();
  49. return 0;
  50. }
  51. static void __exit example_atomic_exit(void)
  52. {
  53. pr_info("example_atomic exit\n");
  54. }
  55. module_init(example_atomic_init);
  56. module_exit(example_atomic_exit);
  57. MODULE_DESCRIPTION("Atomic operations example");
  58. MODULE_LICENSE("GPL");