下面的函数由生产者线程运行。该功能包含重复的代码。如何处理线程函数中的重复代码?
如果它是一个无线程序,我会为重复的代码创建一个单独的函数,并根据需要调用该函数并使用所需的参数。
当线程函数里面的重复代码应该做什么?
// 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