atomic_add_sub.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (C) 2023 Amazon.com Inc. or its affiliates. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <stdio.h>
  6. #include <pthread.h>
  7. #define MAX_NUM_THREADS 4
  8. #define NUM_ITER 100000
  9. int g_add_count = 0;
  10. int g_sub_count = 0;
  11. static void *
  12. thread(void *arg)
  13. {
  14. for (int i = 0; i < NUM_ITER; i++) {
  15. __atomic_fetch_add(&g_add_count, 1, __ATOMIC_SEQ_CST);
  16. __atomic_fetch_sub(&g_sub_count, 1, __ATOMIC_SEQ_CST);
  17. }
  18. return NULL;
  19. }
  20. int
  21. main(int argc, char **argv)
  22. {
  23. pthread_t tids[MAX_NUM_THREADS];
  24. for (int i = 0; i < MAX_NUM_THREADS; i++) {
  25. if (pthread_create(&tids[i], NULL, thread, NULL) != 0) {
  26. printf("Thread creation failed\n");
  27. }
  28. }
  29. for (int i = 0; i < MAX_NUM_THREADS; i++) {
  30. if (pthread_join(tids[i], NULL) != 0) {
  31. printf("Thread join failed\n");
  32. }
  33. }
  34. printf("Value of counter after add update: %d (expected=%d)\n", g_add_count,
  35. MAX_NUM_THREADS * NUM_ITER);
  36. if (g_add_count != MAX_NUM_THREADS * NUM_ITER) {
  37. __builtin_trap();
  38. }
  39. printf("Value of counter after sub update: %d (expected=%d)\n", g_sub_count,
  40. -(MAX_NUM_THREADS * NUM_ITER));
  41. if (g_sub_count != -(MAX_NUM_THREADS * NUM_ITER)) {
  42. __builtin_trap();
  43. }
  44. return -1;
  45. }