Reputation: 1152
I know you have to synchronize your threads to be able to change your global variables content safely in a multithreaded application (where multiple threads are trying to change the variable data at the same time). But is this also necessary if you use a global array, where each thread only uses one of the n elements?
Thanks in advance!
Upvotes: 4
Views: 4185
Reputation: 16597
If a thread is going to access only one array element, there is no need for any synchronization. But it is more likely that you will change you mind and want all the threads to access all the elements of the array. So in that case, the following program will be a good reference to you!
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NOTHREADS 5
/*
The following are the critical sections.
(1) array
(2) array index
*/
int arr[10 * NOTHREADS];
int aindex;
pthread_mutex_t mutex;
void *hello(void *thread_id)
{
int i;
int *id = (int *) thread_id;
for (i=1; i<=10 ; i++) {
pthread_mutex_lock(&mutex);
arr[aindex] = (*id)*100+ i;
sleep(1);
aindex = aindex + 1;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main()
{
pthread_t tids[NOTHREADS];
int ids[NOTHREADS] = {1, 2, 3, 4, 5};
int ret;
long t;
int i;
pthread_mutex_init(&mutex, NULL);
for (i=0 ; i<NOTHREADS; i++) {
printf("%d %s - Creating thread #%d \n", __LINE__, __FUNCTION__, i);
ret = pthread_create(&tids[i], NULL, hello, &ids[i]);
if (ret) {
printf("unable to create thread! \n");
exit(-1);
}
}
for (i=0 ; i<NOTHREADS; i++) {
pthread_join(tids[i], NULL);
}
printf("Final array : \n");
for (i=0; i<50; i++)
printf("%d ", arr[i]);
printf("\n\n");
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
return 0;
}
Upvotes: 1
Reputation: 589
no need for synchronization in your case,you have to make sure read\write operations is performed only by one thread for an element
Upvotes: 0
Reputation: 4752
If no thread is changing the array you may consider it thread-safe. However if two threads access the same array element you should beware of race conditions.
Upvotes: 0
Reputation: 554
No, synchronization is not necessary if the data is not actually shared. That said, beware of false sharing (where a given cache line is being used by multiple threads on different cores), since this can cause performance degradation even though things appear to be working correctly. This is not so much of an issue if you are just reading data from the array.
Upvotes: 3
Reputation: 224859
If each thread only uses one element, and the array's location in memory is never changed, then it's absolutely safe without synchronization.
Upvotes: 7