Below function is run by producer threads. This function contains duplicate code.
Had it been a threadless program, I would have created a separate function for the duplicate code and called that function as per need with desired arguments.
What should be done when the duplicate code in inside the thread's function?
// This function is run by the `Producer` threads.
void *producerThreadFunction (void *arg) {
Q_UNUSED (arg);
while (1) {
pthread_t tId = pthread_self(); qDebug () << "\nProducer: " << tId;
if (sharedQueueA.length () < 10) {
qDebug () << "\nQueue A, First check by Producer: " << tId;
pthread_mutex_lock (&mutexVariable);
if (sharedQueueA.length () < 10) {
sharedQueueA.push_back (1);
qDebug () << "\nPushed by Producer " << tId << ": " << "Length of queue A is: " << sharedQueueA.length ();
}
else {
qDebug () << "\nProducer " << tId << " has no work to do since queue is full, and is now in waiting mode. Length of queue A is: " << sharedQueueA.length ();
pthread_cond_wait (&conditionVariable, &mutexVariable);
}
pthread_mutex_unlock (&mutexVariable);
}
else if (sharedQueueB.length () < 10)
{
qDebug () << "\nQueue B, First check by Producer: " << tId;
pthread_mutex_lock (&mutexVariable);
if (sharedQueueB.length () < 10) {
sharedQueueB.push_back (1);
qDebug () << "\nPushed by Producer " << tId << ": " << "Length of queue is: " << sharedQueueB.length ();
}
else {
qDebug () << "\nProducer " << tId << " has no work to do since quque is full, and is now in waiting mode. Length of queue B is: " << sharedQueueB.length ();
pthread_cond_wait (&conditionVariable, &mutexVariable);
}
pthread_mutex_unlock (&mutexVariable);
}
else
{
qDebug () << "Producer: " << tId << "Both the queues are full. Have to wait!";
}
}
return NULL;
}