atomic_logical.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * Copyright (C) 2023 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <stdio.h>
  6. #include <pthread.h>
  7. // x XOR x -> 0
  8. // even num of thread -> g_val should end up with its original value
  9. #define MAX_NUM_THREADS 4
  10. #define NUM_ITER 199999
  11. int g_val = 5050;
  12. static void *
  13. thread(void *arg)
  14. {
  15. for (int i = 0; i < NUM_ITER; i++) {
  16. __atomic_fetch_xor(&g_val, i, __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("Global value after update: %d (expected=%d)\n", g_val, 5050);
  35. if (g_val != 5050) {
  36. __builtin_trap();
  37. }
  38. return -1;
  39. }