Boost.Thread:为什么要使用多个Boost线程来调度一个用户线程?

时间:2019-03-24 04:03:29

标签: c++ boost boost-thread

我正在使用一个现有的代码库,该代码库模拟一个(简单的)线程调度程序,并使用Boost.Thread库创建用户线程。

对于以前的开发人员(我不可用)的设计选择,我感到困惑。对于每个新用户线程,都会创建一个ThrObjWrapper对象; ThrObjWrapper对象包含4个Boost线程:

  • thrRun
  • thrSuspend
  • thrResume
  • thrSleep

每当线程调度程序(ThrScheduler)恢复或挂起ThrObjWrapper时,ThrObjWrapper都会在其中两个线程上执行操作(这取决于调度程序是恢复还是挂起线程)。

我不知道为什么需要这么多线程。一个增强线程不足够吗?我什至可以理解两个线程,但是四个?为什么是四个?

这是ThrScheduler的执行循环:

// curr = the current ThrObjWrapper instance being run by the ThrScheduler

if (curr != NULL) {
    if (curr->isThrRunning()) {

        if (curr->isThrSuspended())
            curr->thrResume();

    } else {
        curr->run();
    }
}

this->sleepScheduler();

if (curr != NULL && curr->isThrRunning()) {
    curr->thrSuspend();
}

这是ThrObjWrapper类(为简便起见,已删除了互斥量,条件变量,getter / setter等):

class ThrObjWrapper {
    protected:
    bool suspended;

        boost::thread thrRun;
        boost::thread thrSuspend;
        boost::thread thrResume;
        boost::thread thrSleep;
};

void ThrObjWrapper::thrSuspendFunc() {
    this->thrSuspend.interrupt();
    this->thrResume.join();
    this->suspended = true;

    while (this->suspended) {
        this->thrRun.yield();
    }
}

void ThrObjWrapper::thrSuspend() {
    this->thrSleep = boost::thread(&ThrObjWrapper::thrSuspendFunc, this);
}

void ThrObjWrapper::thrResumeFunc() {
    this->thrResume.interrupt();
    this->suspended = false;
    this->thrSleep.join();
}

void ThrObjWrapper::thrResume() {
    this->thrResume = boost::thread(&ThrObjWrapper::thrResumeFunc, this);
}

bool ThreadClass::isThrSuspended() {
    return this->suspended;
}

bool ThrObjWrapper::isThrRunning() {
    return thrRun.joinable();
}

void ThrObjWrapper::thrSleep(int time) {
    this->thrRun.sleep(boost::get_system_time() + boost::posix_time::milliseconds(time));
}

void ThrObjWrapper::run() {
    this->thrRun = boost::thread(&ThrObjWrapper::thrOperation, this);
}

void ThrObjWrapper::thrOperation() {
    // Performs some operation
}

0 个答案:

没有答案