C + + uses instance of TLS thread local storage _c language

Source: Internet
Author: User

The example in this article describes the use of C + + thread local storage. Share to everyone for your reference.

The specific methods are as follows:

Copy Code code as follows:
UseTLS.cpp: Defines the entry point for a console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <process.h>

Statement
VOID Initstarttime ();
DWORD Getusertime ();

TLS index, as global variable
DWORD G_dwtlsindex;

VOID Initstarttime ()
{
DWORD dwstarttime = GetTickCount ();
:: TlsSetValue (G_dwtlsindex, (LPVOID) dwstarttime);
}

DWORD Getusertime ()
{
DWORD dwnowtime = GetTickCount ();
DWORD Dwstarttime = (DWORD):: TlsGetValue (G_dwtlsindex);
return dwnowtime-dwstarttime;
}

UINT WINAPI ThreadProc (LPVOID lpparameter)
{
To simulate a thread's working process
DWORD i = 1000 * 1000 *100;
while (i--)
{
}
printf ("Thread id:%-5d,use time:%d\n",:: GetCurrentThreadID (), Getusertime ());
return 0;
}

int _tmain (int argc, _tchar* argv[])
{
HANDLE HTHREAD[10];
Get TLS index
G_dwtlsindex =:: TlsAlloc ();
Turn on 10 threads to calculate when each thread is running
for (int i=0;i<10;i++)
{
Hthread[i] = (HANDLE) _beginthreadex (null, 0, threadproc, NULL, 0, NULL);
}
Waiting for worker threads
:: WaitForMultipleObjects (Ten, Hthread, TRUE, INFINITE);

for (int i=0;i<10;i++)
{
:: WaitForSingleObject (Hthread[i], INFINITE);
:: CloseHandle (Hthread[i]);
}
Releasing TLS
:: TlsFree (G_dwtlsindex);
return 0;
}

I hope this article will help you with the C + + program design.

Related Article

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.