EXAMPLE: AN ALTERNATIVE THREAD-SAFE DLL STRATEGY
371
There is still a resource leak risk, even with this solution. Some threads, such as
the accept thread, may never terminate and therefore will never be detached
from the DLL.
will call with
but not with for threads that are still active. This does
not cause a problem in this case because the accept thread does not allocate any
resources, and even memory is freed when the process terminates. There would,
however, be an issue if threads allocated resources such as temporary files; the
ultimate solution would be to create a
globally accessible list of resources. The
code would then have the task of scanning the list and
deallocating the resources.
Example: An Alternative Thread-Safe DLL Strategy
Program 12–4, while typical of the way in which TLS and are combined
to create thread-safe libraries, has a weakness that is noted in the comments in
the previous section. In particular, th e state is associated with the thread rather
than with the socket, so a given thread can process only one socket at a time.
An effective alternative
approach to thread-safe library functions is to create a
handle-like structure that is passed to every function call. The state is then main-
tained in the structure. Many UNIX systems use this technique to create thread-
safe C libraries; the main disadvantage is that the functions require a
n additional
parameter for the state structure.
Program 12–5 modi fies Program 12–4. Notice that
is not necessary,
but there are two new functions to initialize and free the state structure. The send
and receive functions require only minimal changes. An associated server,
, is included on the book’s Web site and requires only slight changes
in order to create and close the socket handle (
d enotes handle).
Program 12–5
Thread-Safe DLL with a State Structure
372
CHAPTER 12 NETWORK PROGRAMMING WITH WINDOWS SOCKETS

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.