Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with duplicate code inside a thread function?

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;
}
like image 240
Aquarius_Girl Avatar asked May 21 '26 23:05

Aquarius_Girl


1 Answers

There is nothing special with a thread callback function, other than that thread safety has to be considered. You can call any function from inside a thread, given that the function is thread-safe.

So simply create a function and move the duplicate code there.

like image 158
Lundin Avatar answered May 23 '26 15:05

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!