当前位置:  开发笔记 > 编程语言 > 正文

如何处理线程函数内的重复代码?

如何解决《如何处理线程函数内的重复代码?》经验,为你挑选了1个好方法。

下面的函数由生产者线程运行.此函数包含重复的代码.

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

在线程函数内部重复代码时应该怎么做?

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

Lundin.. 8

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

因此,只需创建一个函数并将重复的代码移动到那里.



1> Lundin..:

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

因此,只需创建一个函数并将重复的代码移动到那里.

推荐阅读
手机用户2502851955
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有