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

📄 sieve.cpp

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

class Sieve : public CMclThreadHandler {
private:
    CMclQueue<int> m_queue;
    Sieve *m_pNext;
    int m_prime;
    CMclThreadAutoPtr m_apThread;
    CMclEvent *m_pStopEvent;

public:
    Sieve(int prime, CMclEvent *pStopEvent) {
        // initialize members...
        m_prime = prime;
        m_pNext = NULL;
        m_pStopEvent = pStopEvent;

        // print the prime...
        cout << setw(8) << prime << flush;

        // create the thread...
        m_apThread = new CMclThread(this);
        assert(m_apThread.IsNull() == FALSE);
    };

    ~Sieve() {
        // delete our child sieve...
        delete m_pNext;
    };

    unsigned ThreadHandlerProc(void) {
        while (TRUE) {
            // get a number to test...
            int n;
            if (m_queue.Get( n, INFINITE, m_pStopEvent) == FALSE)
                break;

            if (n % m_prime) {
                // number might be prime...
                if (m_pNext) {
                    // send the number to the next sieve...
                    m_pNext->Test(n);

                    // relinquish our time slice...
                    Sleep(0);
                }
                else {
                    // no next sieve, number is prime so
                    // it gets it's own sieve...
                    m_pNext = new Sieve( n, m_pStopEvent);
                    assert(m_pNext);
                }
            }
        }

        // we have been told to stop, tell our child 
        // to stop (and indirectly the grandchildren
        // and wait...
        if (m_pNext) {
            m_pNext->Stop();
            m_pNext->m_apThread->Wait(INFINITE);
        }

        return 0;
    };

    void Stop(void) {
        // tell our threads to stop...
        m_pStopEvent->Set();

        // make sure that there is something in the queue to test,
        // this ensures that the thread doesn't get stopped at
        // the Get()...
        // Test(m_prime);

        // wait for the child thread to exit (and its child, on so on)...
        m_apThread->Wait(INFINITE);
    };

    void Test(int n) {
        m_queue.Put(n);
    };
};

int main(int argc, char *argv[]) {
    // construct the stop event...
    CMclEvent cStopEvent( TRUE, FALSE);

    // create the first sieve...
    Sieve s(2, &cStopEvent);

    // send down numbers to test...
    for (int n = 3; n < 200; n++) {
        s.Test(n);
    }

    // give the sieves a little while...
    Sleep(2000);

    // stop the sieves...
    s.Stop();

    return 0;
}

⌨️ 快捷键说明

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