⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bees2.cpp

📁 window下的多线程编程参考书。值得一读
💻 CPP
字号:
#include <stdio.h>
#include "CMcl.h"

#define NUMBER_BEES 4

class BeeHandler : public CMclThreadHandler {
private:
    int m_BeeId;
    BOOL m_bRun;
public:
    BeeHandler(int BeeId) : m_bRun(TRUE), m_BeeId(BeeId) {
    };

    void Stop(void) {
        m_bRun = FALSE;
    };

    unsigned ThreadHandlerProc(void) {
        while (m_bRun) {
            printf( "I am bee #%d.\n", m_BeeId);
        }

        return NO_ERROR;
    };
};

class WorkerBee : public CMclThread {
private:
    BeeHandler *m_pHandler;

    // this constructor is private, use the pseudo-constructor
    // CreateWorkerBee instead...
    WorkerBee(BeeHandler *pHandler) : m_pHandler(pHandler), CMclThread(pHandler) {
    };

public:
    ~WorkerBee() {
        // cleanup the internal thread handler
        delete m_pHandler;
    };

    void Stop(void) {
        // tell the thread handler to stop...
        m_pHandler->Stop();
    };

    // static pseudo constructor dynamically creates a BeeHandler object
    // to pass to the WorkerBee constructor, this allows the WorkerBee
    // to manage the handler and delete it when the WorkerBee is destroyed...
    static WorkerBee *CreateWorkerBee( int BeeId) {
        return new WorkerBee( new BeeHandler(BeeId));
    };
};


int main( int argc, char *argv[]) {
    int i;

    // this is the collection that we will add
    // all of the bee thread objects to...
    CMclWaitableCollection hive;

    // declare thread auto-pointers...
    CMclThreadAutoPtr bee[NUMBER_BEES];

    // create the bees...
    for (i = 0; i < NUMBER_BEES; i++) {
        bee[i] = WorkerBee::CreateWorkerBee(i);
        hive.AddObject(*bee[i]);
    }

    // let the bees buzz..
    Sleep(2000);

    // tell the bees to stop...
    for (i = 0; i < NUMBER_BEES; i++) {
        ///////////////////////////////////////////////////////////////
        // this cast is safe but a bit ugly, we could avoid it by
        // delaring our own WorkerBee version of the
        // thread auto pointer with:
        // typedef CMclDerivedAutoPtr<WorkerBee> CMclWorkerBeeAutoPtr;
        // which would allow us to access the WorkerBee Stop() member
        // function without a cast...
        ///////////////////////////////////////////////////////////////
        WorkerBee & rBee = static_cast<WorkerBee &>(*bee[i]);
        rBee.Stop();
    }

    // wait for the bees...
    hive.Wait( TRUE, INFINITE);

    // all done...
    return NO_ERROR;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -