Say if I have the following C code:
int my_global_arr[100];
or more generally,
some_type *my_global_arr = malloc(some_size * sizeof(some_type);
Is it safe to access (both read and write) different elements concurrently in multiple threads?
For example, if I have
void *my_thread(void *index){
int idx = *((int *)(index));
my_global_arr[idx] = idx;
return NULL;
}
And in main()
int a = 1;
int b = 2;
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, my_thread, &a);
pthread_create(&thread2, NULL, my_thread, &b);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
Will it be guaranteed that the two threads won't interfere with each other?
My experiments:
I tried to run the above "program", expanding to 1000 threads, 100000 times on a x86_64 CPU
with GCC 8.3.0, -std=c99, and it appears that they won't interfere with each other;
however, I don't think such an experiment is good enough to conclude such access is
thread safe on all platform.
Edit 1:
This question is about accessing different elements in different
threads, not the same element in different threads; that is,
for example, thread-1 reads/writes to arr[1]
while thread-2 reads/writes to arr[2].
If you can guaranty that at a time, every element accessed only by one thread, it is the thread-safe. Because every element of the array differ from each other(physically) and it means that they are separated sections of memory.
[Edited]
Accessing different elements of an Array in C is perfectly thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With