zoukankan      html  css  js  c++  java
  • 第二十一章 线程局部存储区

    //1.
    可以使用线程局部存储区(TLS)来将数据与线程关联起来
    
    //2.静态TLS
    #include <windows.h>
    #include <assert.h>
    #include <process.h>
    #include <cstdio>
    
    //静态TLS
    __declspec (thread) int nCount = 0;		
    
    unsigned int __stdcall FunThread0(void* pVoid)
    {
    	int nAddr = reinterpret_cast<int>(&nCount);	//nAddr = 0x00465b84
    	return 0;
    }
    
    unsigned int __stdcall FunThread1(void* pVoid)
    {
    	int nAddr = reinterpret_cast<int>(&nCount);	//nAddr = 0x00465b54
    	return 0;
    }
    
    int main()
    {	
    	HANDLE hThread0 = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, FunThread0, nullptr, 0, nullptr));
    	HANDLE hThread1 = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, FunThread1, nullptr, 0, nullptr));
    	WaitForSingleObject(hThread0, INFINITE);
    	WaitForSingleObject(hThread1, INFINITE);
    	CloseHandle(hThread0);
    	CloseHandle(hThread1);
    
    	return 0;
    }
    
    //3.动态TLS
    #include <windows.h>
    #include <assert.h>
    #include <process.h>
    #include <cstdio>
    
    int nId = 0;
    
    unsigned int __stdcall FunThread0(void* pVoid)
    {
    	if (!TlsSetValue(nId, reinterpret_cast<void*>(1026)))
    	{
    		assert(false);
    	}
    
    	int nTem = reinterpret_cast<int>(TlsGetValue(nId));	//nTem = 1026
    	return 0;
    }
    
    unsigned int __stdcall FunThread1(void* pVoid)
    {
    	if (!TlsSetValue(nId, reinterpret_cast<void*>(1025)))
    	{
    		assert(false);
    	}
    
    	int nTem = reinterpret_cast<int>(TlsGetValue(nId));	//nTem = 1025
    	return 0;
    }
    
    int main()
    {	
    	nId = TlsAlloc();
    	if (-1 == nId)
    	{
    		assert(false);
    	}
    
    	if (!TlsSetValue(nId, reinterpret_cast<void*>(1024)))
    	{
    		assert(false);
    	}
    
    	int nTem = reinterpret_cast<int>(TlsGetValue(nId));	//nTem = 1024
    
    	HANDLE hThread0 = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, FunThread0, nullptr, 0, nullptr));
    	HANDLE hThread1 = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, FunThread1, nullptr, 0, nullptr));
    	WaitForSingleObject(hThread0, INFINITE);
    	WaitForSingleObject(hThread1, INFINITE);
    	CloseHandle(hThread0);
    	CloseHandle(hThread1);
    
    	if (!TlsFree(nId))
    	{
    		assert(false);
    	}
    	return 0;
    }
    
    //4.
    备注:感觉在实际开发中 TLS 没什么鸟用,这里不进行深入研究
    

      

  • 相关阅读:
    在一台服务器上搭建相对高可用HiveServer实践
    HDU 4462 Scaring the Birds (暴力求解,二进制法)
    HDU 4461 The Power of Xiangqi (水题)
    HDU 4460 Friend Chains (BFS,最长路径)
    UVaLive 7270 Osu! Master (统计)
    CodeForces 705C Thor (模拟+STL)
    CodeForces 705B Spider Man (水题)
    CodeForces 705A Hulk (水题)
    UVa 11971 Polygon (数学,转化)
    UVa 10900 So you want to be a 2n-aire? (概率DP,数学)
  • 原文地址:https://www.cnblogs.com/szn409/p/8570182.html
Copyright © 2011-2022 走看看