2015-12-22 66 views
3

下面的函數由生產者線程運行。該功能包含重複的代碼。如何處理線程函數中的重複代碼?

如果它是一個無線程序,我會爲重複的代碼創建一個單獨的函數,並根據需要調用該函數並使用所需的參數。

當線程函數裏面的重複代碼應該做什麼?

// 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; 
} 
+0

BTW RAII'lock_guard'比手動'unlock'更好。 – Jarod42

+0

@ Jarod42哦,那是什麼gaurd_lock?我搜索谷歌w.r.t pthreads gaurd_locks,找不到任何東西。 –

+0

請參閱[lock_guard](http://en.cppreference.com/w/cpp/thread/lock_guard) – Jarod42

回答

8

沒有什麼特別的有螺紋的回調函數,除此之外,線程安全必須考慮。考慮到該函數是線程安全的,您可以從線程內調用任何函數。

因此,只需創建一個函數並將重複代碼移動到那裏。

+0

爲了使新函數線程安全,我必須移動鎖以及等待以及?請解釋。 –

+1

@TheIndependentAquarius您可以將它們移動到新的函數中,或者使用它們圍繞函數調用。無論對你的程序設計最有意義。 – Lundin

+0

噢,所以他們可以移動到新功能?謝謝。順便說一句,嵌套函數呢?應該使用嵌套函數嗎?這會以任何方式獲益嗎? –

相關問題