216
CHAPTER 7 THREADS AND SCHEDULING
Performance
Appendix C includes the results of sorting large files of 64-byte records using one,
two, and four threads. SMP systems give significantly better results. Divide and
conquer is more than just a strategy for algorithm design; it can also be the key to
exploiting thread s and SMP. The single-processor results can vary. On a sy
stem
with limited memory (that is, insufficient physical memory to hold the entire file,
in addition to the OS and other active processes), the use of multiple threads
increases the sort time because the threads contend for available physical
memory. On the other hand, multiple threads can improve performance with a
single processor when there
is sufficient memory. The results are also heavily
dependent on the initial data arrangement, as discussed in Appendix C.
Thread Local Storage
Threads may need to allocate and manage their own storage independently of and
protected from other threads in the same process. One technique is to have the
creating thread call
(or ) with
THREAD LOCAL STORAGE
217
pointing to a data structure that is unique for each thread. The thread can then
a llocate ad ditional data structures and access them through
.
Progra m 7–1 used this technique.
Windows also provides TLS, which gives each thread its own array of pointers.
Figure 7–3 shows this TLS arrangement.
Initially, no TLS indexes (rows) are allocated, but new rows can be allocated
and deallocated at any time, with a maximum of
(at
least 64) indexes for any process. The number of columns can change as new
threads are created and old ones terminate.
The first issue is TLS index management. The primary thread is a logical
place to do this, but any thread can manage thread indexes.
returns the alloca ted index ( 0), with – ( ) if no index
is available.
An individual thread can get and set its values (void pointers) from its slot
using a TLS index.
The programmer must ensure that the TLS index parameter is valid—that is,
that it has been allocated with
and has not been freed.
Figure 7–3 Thread Local Storage within a Process
Thread Number
123
TLS 0
Index 1
2
3
4

Get Windows System Programming Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.