Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <stdlib.h>
  5. #include <stdatomic.h>
  6.  
  7. #define CACHELINE__BYTECOUNT (64)
  8.  
  9. struct Data {
  10. uint8_t bytes[CACHELINE__BYTECOUNT - 4];
  11. atomic_uint_fast64_t u64;
  12. } __attribute__((packed)) __attribute__((aligned ((CACHELINE__BYTECOUNT))));
  13.  
  14. #define VAL1 (0x1111111111111111)
  15. #define VAL2 (0xFFFFFFFFFFFFFFFF)
  16.  
  17. static struct Data data = { .u64 = VAL1 };
  18.  
  19. static void *test_writer(void *unused)
  20. {
  21. (void)unused;
  22. for (uint32_t i = 0; i < 10000; i++) {
  23. for (uint32_t j = 0; j < 1000; j++) {
  24. atomic_store(&data.u64, VAL1);
  25. atomic_store(&data.u64, VAL2);
  26. }
  27. const uint64_t val = atomic_load(&data.u64);
  28. if ((val != VAL1) && (val != VAL2)) {
  29. fprintf(stderr, "ERROR: oh no, got: %lX\n", val);
  30. exit(1);
  31. }
  32. }
  33. return NULL;
  34. }
  35.  
  36. #define NUM_THREADS 4
  37.  
  38. int main(void)
  39. {
  40. pthread_attr_t attr;
  41. {
  42. const int res = pthread_attr_init(&attr);
  43. if (res != 0) {
  44. fprintf(stderr, "ERROR: pthread_attr_init error: %d\n", res);
  45. exit(1);
  46. }
  47. }
  48. struct {
  49. char stack[0x10000];
  50. pthread_t thread;
  51. } threads[NUM_THREADS];
  52. for (uint32_t i = 0; i < NUM_THREADS; i++) {
  53. const int create_res = pthread_create(&threads[i].thread, &attr, test_writer, NULL);
  54. if (create_res != 0) {
  55. fprintf(stderr, "ERROR: pthread_create error: %d\n", create_res);
  56. exit(1);
  57. }
  58. }
  59. {
  60. const int res = pthread_attr_destroy(&attr);
  61. if (res != 0) {
  62. fprintf(stderr, "ERROR: pthread_attr_destroy error: %d\n", res);
  63. exit(1);
  64. }
  65. }
  66. for (uint32_t i = 0; i < NUM_THREADS; i++) {
  67. void *res;
  68. const int join_res = pthread_join(threads[i].thread, &res);
  69. if (join_res != 0) {
  70. fprintf(stderr, "ERROR: pthread_join error: %d\n", join_res);
  71. exit(1);
  72. }
  73. }
  74. printf("SUCCESS\n");
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement