TLS (Thread local storage)

來源:互聯網
上載者:User

Thread local storage (TLS) enables multiple threads of the same process to use an index allocated by the TlsAlloc function to store and retrieve a value that is local to the thread. In this example, an index is allocated when the process starts. When each thread starts, it allocates a block of dynamic memory and stores a pointer to this memory in the TLS slot using the TlsSetValue function. The CommonFunc function uses the TlsGetValue function to access the data associated with the index that is local to the calling thread. Before each thread terminates, it releases its dynamic memory. Before the process terminates, it calls TlsFree to release the index.

 

// TLS.cpp : Defines the entry point for the console application.<br />//</p><p>#include "stdafx.h"<br />#include <Windows.h><br />#include <stdio.h><br />#include <process.h></p><p>//use tls to get time<br />DWORD gtlstime;<br />DWORD InitStartTime();<br />DWORD GetUsrTime();</p><p>UINT __stdcall ThreadFunc(LPVOID)<br />{<br />int i;<br />//initilize time<br />printf("/nThe thread is going to start.Thread id: %-5d, Start time: %d/n", ::GetCurrentThreadId(), InitStartTime());<br /> //InitStartTime();<br />//stimulate to do work<br />i = 10000*10000;<br />while(i--)<br />{</p><p>}</p><p>printf("The thread is going to exit.Thread id: %-5d, Used time: %d/n/n", ::GetCurrentThreadId(), GetUsrTime());<br />return 0;<br />}</p><p>int _tmain(int argc, _TCHAR* argv[])<br />{<br />UINT uid;<br />int i;<br />HANDLE h[10];</p><p>gtlstime = ::TlsAlloc();</p><p>for (i=0; i<10; i++)<br />{<br />//::Sleep(10);<br />h[i] = (HANDLE)::_beginthreadex(NULL, 0, ThreadFunc, NULL, 0, &uid);<br />}</p><p>for (i=0; i<10; i++)<br />{<br />::WaitForSingleObject(h[i], INFINITE);<br />::CloseHandle(h[i]);<br />}</p><p>::TlsFree(gtlstime);<br />getchar();<br />return 0;<br />}</p><p>DWORD InitStartTime()<br />{<br />DWORD dwstart = ::GetTickCount();<br />::TlsSetValue(gtlstime, (LPVOID)dwstart);<br />return dwstart;<br />}</p><p>DWORD GetUsrTime()<br />{<br />DWORD dwend;<br />dwend = ::GetTickCount();<br />dwend = dwend - (DWORD)::TlsGetValue(gtlstime);<br />return dwend;<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.