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

📄 tls.cpp

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

#define NUM_THREADS         10
#define THREAD_LIFETIME     1000

// index for dynamically allocated TLS...
DWORD g_dwDynamicTLSIndex;

// storage for statically allocated TLS...
__declspec(thread) DWORD gt_dwStaticTLSCount = 0;

void foo(void) {
    // read the current dynamic TLS value...
    DWORD dwValue = (DWORD) TlsGetValue(g_dwDynamicTLSIndex);

    // add one to the count...
    dwValue++;

    // save the new value back to dynamic TLS...
    if (!TlsSetValue( g_dwDynamicTLSIndex, (LPVOID) dwValue)) {
        printf( "Error! Unable to increment TLS value, error = %ld.\n", GetLastError());
    }

    // increment the current thread's statically
    // allocated TLS counter...
    gt_dwStaticTLSCount++;
}

DWORD get_dynamic_TLS_count(void) {
    return (DWORD) TlsGetValue(g_dwDynamicTLSIndex);
}

DWORD get_static_TLS_count(void) {
    return (DWORD) gt_dwStaticTLSCount;
}

class CFooThreadHandler : public CMclThreadHandler {
    unsigned ThreadHandlerProc(void) {
        // run the thread for a short time...
        clock_t endtime = clock() + THREAD_LIFETIME;
        while (clock() < endtime) {
            foo();
        }

        // print out the count and thread info...
        printf( "Thread ID=0x%08x foo() call count: %ld (dynamic TLS) / %ld (static TLS).\n", 
            GetCurrentThreadId(), 
            get_dynamic_TLS_count(),
            get_static_TLS_count());
        return 0;
    };
};

int main( int argc, char *argv[]) {
    // allocate the dynamic TLS index...
    g_dwDynamicTLSIndex = TlsAlloc();
    if (g_dwDynamicTLSIndex == TLS_OUT_OF_INDEXES) {
        printf( "Fatal Error - no indexes left!\n");
        return (-1);
    }
    
    // create some threads that use counted_function()...
    // notice that all the threads use the same instance
    // of the thread handler object...
    int i;
    CMclWaitableCollection cCollection;
    CFooThreadHandler cFooHandler;
    CMclThreadAutoPtr apThread[NUM_THREADS];
    for (i = 0; i < NUM_THREADS; i++) {
        apThread[i] = new CMclThread(&cFooHandler);
        cCollection.AddObject(*apThread[i]);
    }

    // allow the threads to run...
    cCollection.Wait( TRUE, INFINITE);

    // free the dynamic TLS index...
    if (!TlsFree(g_dwDynamicTLSIndex)) {
        printf( "Error - unable to release TLS index!\n");
        return (-1);
    }

    return 0;
}

⌨️ 快捷键说明

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