I am using array
with 2 threads. One is writing to it and another reading. You can assume that reading is slower than writing. The reader and writer are separate pthreads
. As far as I know sharing an array
as a global variable between those threads is safe.
So overall picture is like:
char ** array;
void writer(void){
for (unsigned long i = 0; i < maxArraySize; i++){
array[i] = malloc(someSize);
array[i] = someCharArray;
}
void reader(void){
for (unsigned long i = 0; i < maxArraySize; i++){
if(array[i] == NULL){ // in case reader is faster
i--;
continue;
}
useData(array[i]);
free(array[i]); // HERE IS MY QUESTION..
}
main(){
array = malloc(maxArraySize);
pthread_t reader, writer;
pthread_create( &reader, NULL, reader, NULL);
pthread_create( &writer, NULL, writer, NULL);
}
My question is related with line where I free i'th element of array. Is it safe to do it? Because when I free i'th element, at the same time, write is writing to array. So can there be a case that writer gets wrong address as it can lose the head pointer?