【问题标题】:How to deal with duplicate code inside a thread function?如何处理线程函数中的重复代码?
【发布时间】:2015-12-22 09:58:33
【问题描述】:

以下函数由生产者线程运行。此函数包含重复代码。

如果它是一个无线程程序,我会为重复代码创建一个单独的函数,并根据需要使用所需的参数调用该函数。

线程函数内部出现重复代码怎么办?

//  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 哦,那个 gaurd_lock 是什么?我搜索了谷歌 w.r.t pthreads gaurd_locks,找不到任何东西。

标签: c++ c multithreading pthreads


【解决方案1】:

线程回调函数没有什么特别之处,除了必须考虑线程安全之外。您可以从线程内部调用任何函数,前提是该函数是线程安全的。

所以只需创建一个函数并将重复的代码移到那里。

【讨论】:

  • 为了使新函数线程安全,我也必须移动锁并等待?请解释一下。
  • @TheIndependentAquarius 您可以将它们移动到新函数中,或者用它们包围函数调用。任何对你的程序设计最有意义的东西。
  • 哦,所以他们可以移动到新功能?谢谢。顺便说一句,嵌套函数呢?应该使用嵌套函数吗?这会有什么好处吗?
  • @TheIndependentAquarius “线程回调函数没有什么特别之处,除了必须考虑线程安全之外。”如果有意义,请使用嵌套函数。
猜你喜欢
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多