下面的函數由生產者線程運行。該功能包含重複的代碼。如何處理線程函數中的重複代碼?
如果它是一個無線程序,我會爲重複的代碼創建一個單獨的函數,並根據需要調用該函數並使用所需的參數。
當線程函數裏面的重複代碼應該做什麼?
// 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;
}
BTW RAII'lock_guard'比手動'unlock'更好。 – Jarod42
@ Jarod42哦,那是什麼gaurd_lock?我搜索谷歌w.r.t pthreads gaurd_locks,找不到任何東西。 –
請參閱[lock_guard](http://en.cppreference.com/w/cpp/thread/lock_guard) – Jarod42