思うだけで学ばない日記 2.0

思うだけで学ばない日記から移転しました☆!よろしくお願いします。

Anytime, Anywhere マルチスレッド

春に書いたスレッドプールがアレな出来だったので書き直してみまくりんぐ、

うれしげに貼る

#include "stdafx.h"
#include "dbg.h"

#include "mythread_cfg.h"
#include "MyThreadPool.h"

namespace DbgMyThreadPool
{
    /// 文字列を反復出力するサンプルスレッドです。
    class SampleThread : public MyThread
    {
    private:
        string msg;
        int cnt;
        volatile bool quit;

        static CCritSec syncRoot;

    public:
        SampleThread(string s, int c) : msg(s), cnt(c), quit(false) { }

        void ThreadFunc()
        {
            for (int i = 0; i < cnt; ++i) {
                if (quit)
                    return;
                PrintMsg(i + 1);
                Sleep(5);           // 無くても動くが、1スレッドが終了までcoutを占有しっぱなしでほぼ順序動作になる。
            }
        }

        void SetQuit() { quit = true; }

        void ClrQuit() { quit = false; }

    private:
        void PrintMsg(int k)
        {
            CAutoLock lock(&syncRoot);
            cout << dec << noshowpos << "[" << k << "] " << msg << endl;
        }

    };

    // 同期オブジェクト実体
    CCritSec SampleThread::syncRoot;

    // スレッドオブジェクト実体
    static SampleThread thread1("Core 1", 300);
    static SampleThread thread2("Core 2", 300);
    static SampleThread thread3("Core 3", 300);
    static SampleThread thread4("Core 4", 300);
    static SampleThread thread5("Core 5", 300);
    static SampleThread thread6("Core 6", 300);
    static SampleThread thread7("Core 7", 300);
    static SampleThread thread8("Core 8", 300);

    bool chkConstruction()
    {
        MyThreadPool thp;
        cout << dec << noshowpos << "MaxThreads=" << thp.GetMaxThreads() << endl;
        return true;
    }

    bool chkSynchronizing()
    {
        MyThreadPool thp;
        cout << dec << noshowpos << "MaxThreads=" << thp.GetMaxThreads() << endl;

        // スレッド起動
        MyThread* pThreads[16];
        HANDLE tevts[16];
        int n = 0;
        pThreads[n++] = &thread1;
        pThreads[n++] = &thread2;
        pThreads[n++] = &thread3;
        pThreads[n++] = &thread4;
        pThreads[n++] = &thread5;
        pThreads[n++] = &thread6;
        pThreads[n++] = &thread7;
        pThreads[n++] = &thread8;
        int cnt = thp.Exec(pThreads, n, tevts);     // 空いているスレッドを最大n個確保、実行開始

        // 全部終了するのを待つ
        //Sleep(10 * 1000);                           // 完全終了後にWaiTerm()してもおk
        thp.WaiTerm(tevts, cnt);

        return true;
    }

}   // DbgMyThreadPool

実行結果。

MaxThreads=8
[1] Core 1
[1] Core 2
[1] Core 5
[1] Core 4
[1] Core 6
[1] Core 7
[1] Core 8
[1] Core 3
[2] Core 8
[2] Core 4
[2] Core 5
[2] Core 7
[2] Core 1
[2] Core 3
[2] Core 6
[2] Core 2
[3] Core 6
[3] Core 2
[3] Core 4
[3] Core 3
[3] Core 5
[3] Core 1
[3] Core 8
[3] Core 7
(…中略…)
[299] Core 6
[299] Core 3
[299] Core 4
[299] Core 5
[299] Core 7
[299] Core 8
[299] Core 1
[299] Core 2
[300] Core 6
[300] Core 5
[300] Core 4
[300] Core 3
[300] Core 8
[300] Core 7
[300] Core 2
[300] Core 1