Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is access to different elements in a C array thread safe?

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].

like image 560
user12986714 Avatar asked Oct 27 '25 02:10

user12986714


2 Answers

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.

like image 65
SpongeBob Avatar answered Oct 29 '25 17:10

SpongeBob


[Edited]

Accessing different elements of an Array in C is perfectly thread safe.

like image 43
Abhijeet Kale Avatar answered Oct 29 '25 18:10

Abhijeet Kale