• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * tls.cpp
3  */
4 
5 #define WIN32_LEAN_AND_MEAN
6 #include <windows.h>
7 #include <iostream>
8 #include <process.h>
9 
10 
11 int __thread tls_value = 0;
12 
thread_fn(void *)13 unsigned __stdcall thread_fn(void*)
14 {
15 	++tls_value;
16 	return 0;
17 }
18 
19 // This is derived from the jig that I setup to explore the problems with
20 // MT exception handling - you could probably just as easily set processors to
21 // some value rather than tying it to the actual # of cores...
main()22 int main()
23 {
24 	// Get the number of processors available to use
25 	SYSTEM_INFO si;
26 	GetSystemInfo(&si);
27 	const unsigned processors = si.dwNumberOfProcessors;
28 
29 	// Make a thread for every processor and assign the thread to it
30     HANDLE threads[processors];
31     unsigned i;
32     for (i=0;i<processors;i++) {
33     	threads[i] = (HANDLE)_beginthreadex(0, 0, thread_fn, 0, CREATE_SUSPENDED, 0);
34     	SetThreadAffinityMask(threads[i], 1 << i);
35     }
36     // Restart all the threads
37     for (i=0;i<processors;i++)
38     	ResumeThread(threads[i]);
39     // Rejoin those threads
40 	WaitForMultipleObjects(processors, threads, 1, INFINITE);
41 	for (i=0;i<processors;i++)
42 		CloseHandle(threads[i]);
43 
44 	std::cout << "How is it possible that tls_value is "
45           << tls_value << " != 0 ?" << std::endl;
46 
47 	return 0;
48 }
49