example_atomic.c 1.8 KB

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