Thread-local Storage (TLS)

Source: Internet
Author: User

The following example demonstrates how to set a DLL to support TLS.

#include <Windows.h>
This is the shared slot
Static DWORD Gdwtlsslot;
BOOL DllMain (hinstance hinst, DWORD fdwreason, LPVOID lpreserved)
{
LPVOID lpdata;
Unreferenced_parameter (hinst);
Unreferenced_parameter (lpreserved);
Switch (Fdwreason)
{
Case Dll_process_attach:
Find the index that'll be global for all threads
Gdwtlsslot = TlsAlloc ();
if (Gdwtlsslot = = 0xFFFFFFFF)
return FALSE;
Fall through to handle thread attach too
Case Dll_thread_attach:
Initialize the TLS index for this thread.
lpdata = (LPVOID) LocalAlloc (lptr, sizeof (struct ourdata));
if (lpdata! = NULL)
if (TlsSetValue (Gdwtlsslot, lpdata) = = FALSE)
;//this should be handled
Break
Case Dll_thread_detach:
Release the allocated memory for this thread.
lpdata = TlsGetValue (Gdwtlsslot);
if (lpdata! = NULL)
LocalFree ((hlocal) lpdata);
Break
Case Dll_process_detach:
Release the allocated memory for this thread.
lpdata = TlsGetValue (Gdwtlsslot);
if (lpdata! = NULL)
LocalFree ((hlocal) lpdata);
Give back the TLS slot
TlsFree (Gdwtlsslot);
Break
Default
Break
}
return TRUE;
}

the _declspec (thread) has thread locality, is unique for each thread.

Example: _declspec (thread) DWORD gprogresscounter;

can also be used on the structure of the body. To change the DWORD to struct type.

Limitations of _DECLSPEC (thread)

First:


Second:

A DLL If you use the _decls pec (thread), there is no way to be loaded by LoadLibrary (). Because the size calculation of a thread's local section is done at program startup, there is no way to recalculate a new DLL when it is loaded.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Thread-local Storage (TLS)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.