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

📄 gtptest.cpp

📁 window下的多线程编程参考书。值得一读
💻 CPP
字号:
//
// FILE: GTPTest.cpp
//
// Copyright (c) 1997 by Aaron Michael Cohen and Mike Woodring
//
/////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>
#include "CGrowableThreadPool.h"

// Thread handler that will be used for all threads dispatched
// from the thread pool.
//
class CGrowablePoolThreadHandler : public CMclThreadHandler
{
    public:
        virtual unsigned ThreadHandlerProc()
        {
            // Do some "work" by sleeping between 1 and 2 seconds.
            //
            srand(GetCurrentThreadId());

            DWORD dwWorkPeriod = (1000 + (rand() % 1000));

            printf(
                "[0x%08lx] Thread has been dispatched.  Sleeping %dms.\n",
                GetCurrentThreadId(),
                dwWorkPeriod
            );

            Sleep(dwWorkPeriod);

            printf(
                "[0x%08lx] Thread is done executing.  Returning to the pool or exiting.\n",
                GetCurrentThreadId()
            );

            return(0);
        }
 };

void main( void )
{
    #define MIN_THREADS         3
    #define MAX_THREADS         6
    #define THREAD_TIMEOUT      5000

    CGrowableThreadPool         ThreadPool(MIN_THREADS, MAX_THREADS, THREAD_TIMEOUT);
    CGrowablePoolThreadHandler  ThreadHandler;

    printf(
        "[0x%08lx] Primary thread is dispatching jobs...\n",
        GetCurrentThreadId()
    );

    // Try to purposefully dispatch 3 more threads than we have in the
    // pool.
    //
    for( int i = 0; i < (MAX_THREADS + 3); i++ )
    {
        if( ThreadPool.DispatchThread(&ThreadHandler) )
        {
            printf(
                "[0x%08lx] Dispatched thread successfully\n",
                GetCurrentThreadId()
            );
        }
        else
        {
            printf(
                "[0x%08lx] Failed to dispatch thread - pool limit reached.\n",
                GetCurrentThreadId()
            );
        }
    }

    // Go to sleep for a while so that we can watch the
    // threads decay and terminate themselves.
    //
    Sleep(15000);

    printf(
        "[0x%08lx] Primary thread exiting.\n",
        GetCurrentThreadId()
    );
}

⌨️ 快捷键说明

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