main_global_atomic.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 1000
  9. int g_count = 0;
  10. static void *
  11. thread(void *arg)
  12. {
  13. for (int i = 0; i < NUM_ITER; i++) {
  14. __atomic_fetch_add(&g_count, 1, __ATOMIC_SEQ_CST);
  15. }
  16. return NULL;
  17. }
  18. int
  19. main(int argc, char **argv)
  20. {
  21. pthread_t tids[MAX_NUM_THREADS];
  22. for (int i = 0; i < MAX_NUM_THREADS; i++) {
  23. if (pthread_create(&tids[i], NULL, thread, NULL) != 0) {
  24. printf("Thread creation failed\n");
  25. }
  26. }
  27. for (int i = 0; i < MAX_NUM_THREADS; i++) {
  28. if (pthread_join(tids[i], NULL) != 0) {
  29. printf("Thread join failed\n");
  30. }
  31. }
  32. printf("Value of counter after update: %d (expected=%d)\n", g_count,
  33. MAX_NUM_THREADS * NUM_ITER);
  34. if (g_count != MAX_NUM_THREADS * NUM_ITER) {
  35. __builtin_trap();
  36. }
  37. return -1;
  38. }