[並發並行]_[C/C++]_[使用執行緒區域儲存Thread Local Storage(TLS)-win32和pthread比較],-win32pthread
情境:
1. 需要統計某個線程的對象上建立的個數.
2. 當建立的堆空間需要根據線程需要建立和結束時銷毀時.
3. 因為範圍是線程只能看到自己的儲存資料,所以不需要臨界區或互斥量來維護自己的堆記憶體. 加入如果用全域std::map實現,那麼必須在put和get時加鎖,這是很損耗資源的.
4. 可以用在維護一個串連,比如socket,database串連.
說明:
1. Java也有自己的執行緒區域儲存ThreadLocal
2. pthread的win32版本: http://sourceware.org/pthreads-win32/
例子test_TSL.cpp:
#include "stdafx.h"#include <stdio.h>#include <stdint.h>#include <stdlib.h>#include <assert.h> #include <windows.h> #include "pthread.h"#define THREADCOUNT 4 DWORD dwTlsIndex; VOID ErrorExit(const char*); static pthread_barrier_t barrier = NULL;static pthread_once_t random_is_initialized = PTHREAD_ONCE_INIT;static pthread_key_t key;VOID CommonFunc(VOID) { LPVOID lpvData; // Retrieve a data pointer for the current thread. lpvData = TlsGetValue(dwTlsIndex); if ((lpvData == 0) && (GetLastError() != ERROR_SUCCESS)) ErrorExit("TlsGetValue error"); // Use the data stored for the current thread. int64_t* value = (int64_t*)lpvData; printf("common: thread %d: lpvData=%lx : value=%lld\n", GetCurrentThreadId(), lpvData,*value); Sleep(5000); } DWORD WINAPI ThreadFunc(VOID) { LPVOID lpvData; // Initialize the TLS index for this thread. lpvData = (LPVOID) LocalAlloc(LPTR, 8); if (! TlsSetValue(dwTlsIndex, lpvData)) ErrorExit("TlsSetValue error"); int64_t* value = (int64_t*)lpvData; *value = GetCurrentThreadId(); printf("thread %d: lpvData=%lx\n", GetCurrentThreadId(), lpvData); CommonFunc(); // Release the dynamic memory before the thread returns. lpvData = TlsGetValue(dwTlsIndex); if (lpvData != 0) LocalFree((HLOCAL) lpvData); return 0; }void TestWin32TLS(){ DWORD IDThread; HANDLE hThread[THREADCOUNT]; int i; // Allocate a TLS index. if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES) ErrorExit("TlsAlloc failed"); //1. 注意,這個dwTlsIndex 並不是從0開始. printf("dwTlsIndex %ld\n",dwTlsIndex);// Create multiple threads. for (i = 0; i < THREADCOUNT; i++) { hThread[i] = CreateThread(NULL, // default security attributes 0, // use default stack size (LPTHREAD_START_ROUTINE) ThreadFunc, // thread function NULL, // no thread function argument 0, // use default creation flags &IDThread); // returns thread identifier // Check the return value for success. if (hThread[i] == NULL) ErrorExit("CreateThread error\n"); } for (i = 0; i < THREADCOUNT; i++) WaitForSingleObject(hThread[i], INFINITE); TlsFree(dwTlsIndex);}void CommonFuncPthread(void) { void* lpvData = pthread_getspecific(key); int64_t* value = (int64_t*)lpvData; printf("common: thread %d: lpvData=%lx : value=%lld\n", GetCurrentThreadId(), lpvData,*value); }void* StartPthread(void* data){int64_t *buf = (int64_t*)malloc(256);*buf = GetCurrentThreadId();pthread_setspecific(key, buf);CommonFuncPthread();free(buf); pthread_barrier_wait(&barrier);return NULL;}//1.只調用一次,可以放在隨意一個work thread執行函數裡都可以,會隨機找一個線程執行.//2.類似win32的DLL_PROCESS_ATTACH只執行一次.void TestPthreadTLS(){pthread_key_create(&key, NULL);pthread_barrier_init(&barrier,NULL, THREADCOUNT + 1); for(int i = 0; i< THREADCOUNT; ++i){pthread_t t;pthread_create(&t,NULL,StartPthread,NULL);pthread_detach(t);}//1.等待其他線程執行完.pthread_barrier_wait(&barrier);pthread_key_delete(key);}DWORD main(VOID) { //1.win32TLS printf("TestWin32TLS\n"); TestWin32TLS(); //1.pthread TLS printf("TestPthreadTLS\n"); TestPthreadTLS(); return 0; } VOID ErrorExit (const char* lpszMessage) { fprintf(stderr, "%s\n", lpszMessage); ExitProcess(0); }
.
輸出:
TestWin32TLSdwTlsIndex 26thread 8452: lpvData=714f50common: thread 8452: lpvData=714f50 : value=8452thread 8460: lpvData=7153d0common: thread 8460: lpvData=7153d0 : value=8460thread 8456: lpvData=715610common: thread 8456: lpvData=715610 : value=8456thread 8464: lpvData=715190common: thread 8464: lpvData=715190 : value=8464TestPthreadTLScommon: thread 8520: lpvData=3b4eb0 : value=8520common: thread 8512: lpvData=3b4ff0 : value=8512common: thread 8516: lpvData=3b4eb0 : value=8516common: thread 8524: lpvData=3b4ff0 : value=8524
參考:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686749(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686991(v=vs.85).aspx
http://blog.chinaunix.net/uid-10231348-id-3034751.html
http://blog.csdn.net/liulina603/article/details/17991731
http://linux.die.net/man/3/pthread_once