Reputation: 741
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]
.
Upvotes: 4
Views: 2158
Reputation: 1
The question is a good one. If the basic operations of the cpu work on 32bit pieces of memory, then in thread 1 the cpu would read 32 bits, update the left 16 and then write back 32 bits. This would overwrite the right 16 which could have been changed by thread 2 between the thread 1 read and write. However we hope that the author of the original question is not the first person to think of this and in the real world steps are taken by compiler writers to emit the correct code. Easiest would be to align the array elements on 32 bit boundaries even though the size is 16.
Upvotes: 0
Reputation: 31
[Edited]
Accessing different elements of an Array in C is perfectly thread safe.
Upvotes: 3
Reputation: 464
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.
Upvotes: 3