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

📄 classicdining.cpp

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

enum { NUMBER_PHILOSOPHERS = 5 };

class CTable {
private:
    CMclMutex m_cmForks[NUMBER_PHILOSOPHERS];
    BOOL m_bContinue;

public:
    CTable() {
        m_bContinue = TRUE;
    };

    void TakeForks(int nId) {
        m_cmForks[nId].WaitForTwo( m_cmForks[(nId + 1) % NUMBER_PHILOSOPHERS], TRUE, INFINITE);
    };

    void DropForks(int nId) {
        m_cmForks[nId].Release();
        m_cmForks[(nId + 1) % NUMBER_PHILOSOPHERS].Release();
    }

    BOOL Continue(void) {
        return m_bContinue;
    };

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

class CPhilosopher : public CMclThreadHandler {
private:
    int m_nId;
    CTable *m_pTable;

public:
    CPhilosopher( int nId, CTable *pt) :    m_nId(nId), 
                                            m_pTable(pt) {
        return;
    };
    
    unsigned ThreadHandlerProc(void) {
        Philosophize();
        return 0;
    }

    void Philosophize(void) {
        while (m_pTable->Continue()) {
            m_pTable->TakeForks(m_nId);            
            Eat();
            m_pTable->DropForks(m_nId);
            Think();
        }

        printf( "Philosopher %d is done.\n", m_nId);
    };

    void Think(void) {
        printf( "Philosopher %d Thinking.\n", m_nId);
        Sleep(rand() % 100);
    };

    void Eat(void) {
        printf( "Philosopher %d Eating.\n", m_nId);
        Sleep(rand() % 100);
    };
};

class CPhilosopherThread : public CMclThread {
private:
    CPhilosopher *m_pPhilosopher;
    
private:
    CPhilosopherThread( CPhilosopher *pPhilosopher) : CMclThread(pPhilosopher) {
        m_pPhilosopher = pPhilosopher;
    };

public:
    ~CPhilosopherThread() {
        delete m_pPhilosopher;
    };

    static CPhilosopherThread *CreatePhilosopher( int nId, CTable *pt) {
        CPhilosopher *pPhilosopher = new CPhilosopher( nId,pt);
        return new CPhilosopherThread(pPhilosopher);
    }
};

int main( int argc, char *argv[]) {
    int i;
    CTable table;
    CMclThreadAutoPtr cPhilosophers[NUMBER_PHILOSOPHERS];
    CMclWaitableCollection collection;

    for (i = 0; i < NUMBER_PHILOSOPHERS; i++) {
        cPhilosophers[i] = CPhilosopherThread::CreatePhilosopher(i, &table);
        collection.AddObject(*cPhilosophers[i]);
    }

    // run for 5 seconds...
    Sleep(5000);

    table.Stop();
    collection.Wait( TRUE, INFINITE);

    printf( "All done.\n");

    return 0;
}

⌨️ 快捷键说明

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