2015-12-22 59 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

噢,所以他们可以移动到新功能?谢谢。顺便说一句,嵌套函数呢?应该使用嵌套函数吗?这会以任何方式获益吗? –

相关问题