I have a problem with using atomic variables in memory pool. See the short code below, it causes a segfault. Curiously enough it happens only for bigger integer types, for atomic_int and atomic_uint all works well!
I am using stock clang on an M1 ARM64 OS X, can anyone reproduce this under other OS/compilers? Is it clang specific?
#include <stdio.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <assert.h>
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
typedef struct AtomTest {
atomic_ulong atomic_count; // atomic variable
int64_t non_atomic_count; // non-atomic variable
} AtomTest;
size_t chunkSize = 0;
int main(void)
{
chunkSize = MAX(sizeof(AtomTest), 300);
uint8_t *memory = malloc(100000 * chunkSize);
assert(memory);
for(int i=0; i<100000; i++) {
AtomTest *aa = (AtomTest *)(memory + chunkSize * i);
aa->atomic_count = 0;
/* tried this instead, same result: */
/* atomic_store_explicit (&(aa->atomic_count), 0, memory_order_relaxed); */
/* tried this instead, same result: */
/* atomic_init (&(aa->atomic_count), 0); */
aa->non_atomic_count = 0;
}
for(int i=0; i<100000; i++) {
AtomTest *aa = (AtomTest *)(memory + chunkSize * i);
printf("The atomic counter is: %lu\n", aa->atomic_count);
printf("The non-atomic counter is: %llu\n", aa->non_atomic_count);
}
}
Surprisingly, in LLDB I can see the segfault but somehow I can access the variable from lldb directly:
Process 26353 launched: '/Users/mareklipert/Documents/prog/clojure/clojure-rt/llvm/runtime/atomic' (arm64)
Process 26353 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=257, address=0x10180012c)
frame #0: 0x0000000100003e88 atomic`main at atomic.c:23:24
20 assert(memory);
21 for(int i=0; i<100000; i++) {
22 AtomTest *aa = (AtomTest *)(memory + chunkSize * i);
-> 23 aa->atomic_count = 0;
24 /* tried this instead, same result: */
25 /* atomic_store_explicit (&(aa->atomic_count), 0, memory_order_relaxed); */
26 /* tried this instead, same result: */
Target 0: (atomic) stopped.
(lldb) po &(aa->atomic_count)
0x000000010180012c
(lldb) po aa->atomic_count
0