While working in a multi-threaded environment, then data sharing seems to be a good option to pass data between threads.
While working with real time systems it is apparently advisable to go with memory optimization.
So, in my scenario, I have one consumer and one producer. They share one queue of any data type
e.g int queue. Now the producer generates data & copies the data to the queue and emits a signal to the consumer who is waiting for the signal as following:
thread 1: pthread_mutex_lock(&mutex); while (!condition) pthread_cond_wait(&cond, &mutex); /* do something that requires holding the mutex and condition is true */ pthread_mutex_unlock(&mutex); thread2: pthread_mutex_lock(&mutex); /* do something that might make condition true */ pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex);
Once the producer generates the data into the queue and emits a signal, then the consumer gets that signal & locks the queue to enter into a critical section.
Now, does the consumer need to copy that data or directly process that data in the critical section? Which option is advisable?
Consider a real time example, my producer thread generates data at every
50ms and as per code, locks the queue at every 50ms, copies data into the queue, emits a signal and unlocks.
Once the consumer receives the signal, it has to process the data. But, before processing the data, the consumer internally first locks the queue.
So, before the data is processed, should it be copied first or can it be directly processed and then unlocked ?
FYI, the consumer takes only 1ms of time to process.
In this scenario, is memory copying more efficient or is it the pointer to memory ?