15,471
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <process.h>
static DWORD m_dwTLSIndex = 0;
static CRITICAL_SECTION m_lock;
#define MAX_ALLOCATE 1000000u
static volatile DWORD m_dwAllocCount = 0;
struct BUFFER
{
BUFFER *next;
BYTE data[16];
};
struct BUFFER_LIST
{
BUFFER_LIST *next;
BUFFER *pBuffers;
};
static BUFFER_LIST *m_pBufferList = NULL;
static BUFFER *m_pBuffers = NULL;
uintptr_t __stdcall _thread1(void *)
{
BUFFER *p;
BUFFER_LIST *pList = (BUFFER_LIST *)malloc(sizeof(BUFFER_LIST));
ZeroMemory(pList, sizeof(BUFFER_LIST));
::EnterCriticalSection(&m_lock);
pList->next = m_pBufferList;
m_pBufferList = pList;
::LeaveCriticalSection(&m_lock);
::TlsSetValue(m_dwTLSIndex, pList);
for (;;)
{
p = (BUFFER *)malloc(sizeof(BUFFER));
p->data[0] = 0;
pList = (BUFFER_LIST *)::TlsGetValue(m_dwTLSIndex);
p->next = pList->pBuffers;
pList->pBuffers = p;
if (InterlockedIncrement(&m_dwAllocCount) >= MAX_ALLOCATE)
break;
}
return 0;
}
uintptr_t __stdcall _thread2(void *)
{
BUFFER *p;
for (;;)
{
p = (BUFFER *)malloc(sizeof(BUFFER));
p->data[0] = 0;
::EnterCriticalSection(&m_lock);
p->next = m_pBuffers;
m_pBuffers = p;
::LeaveCriticalSection(&m_lock);
if (InterlockedIncrement(&m_dwAllocCount) >= MAX_ALLOCATE)
break;
}
return 0;
}
void TestTLSData()
{
::InitializeCriticalSection(&m_lock);
ULONGLONG ullBegin, ullEnd;
SYSTEM_INFO si;
::GetSystemInfo(&si);
DWORD dwThread = 0;
DWORD dwCount = si.dwNumberOfProcessors;
HANDLE *phThreads = new HANDLE[dwCount + 1];
ZeroMemory(phThreads, sizeof(HANDLE) * (dwCount + 1));
m_dwTLSIndex = ::TlsAlloc();
::GetSystemTimeAsFileTime((LPFILETIME)&ullBegin);
dwThread = 0;
while (dwCount--)
phThreads[dwThread++] = (HANDLE)_beginthreadex(NULL, 0, _thread1, NULL, 0, NULL);
::WaitForMultipleObjects(dwThread, phThreads, TRUE, INFINITE);
::GetSystemTimeAsFileTime((LPFILETIME)&ullEnd);
printf("Used TLS: %u.%04u ms\n", (DWORD)(ullEnd - ullBegin) / 10000, (DWORD)(ullEnd - ullBegin) % 10000);
while (dwThread--)
::CloseHandle(phThreads[dwThread]);
::TlsFree(m_dwTLSIndex);
BUFFER *n, *p;
//BUFFER_LIST *pNext;
//BUFFER_LIST *pList = m_pBufferList;
//while (pList != NULL)
//{
// pNext = pList->next;
// p = pList->pBuffers;
// while (p)
// {
// n = p->next;
// free(p);
// p = n;
// }
// free(pList);
// pList = pNext;
//}
m_dwAllocCount = 0;
dwCount = si.dwNumberOfProcessors;
ZeroMemory(phThreads, sizeof(HANDLE) * (dwCount + 1));
::GetSystemTimeAsFileTime((LPFILETIME)&ullBegin);
dwThread = 0;
while (dwCount--)
phThreads[dwThread++] = (HANDLE)_beginthreadex(NULL, 0, _thread2, NULL, 0, NULL);
::WaitForMultipleObjects(dwThread, phThreads, TRUE, INFINITE);
::GetSystemTimeAsFileTime((LPFILETIME)&ullEnd);
printf("Not used TLS: %u.%04u ms\n", (DWORD)(ullEnd - ullBegin) / 10000, (DWORD)(ullEnd - ullBegin) % 10000);
while (dwThread--)
::CloseHandle(phThreads[dwThread]);
//p = m_pBuffers;
//while (p)
//{
// n = p->next;
// free(p);
// p = n;
//}
::DeleteCriticalSection(&m_lock);
system("pause");
}