EXAMPLE: AN ALTERNATIVE THREAD-SAFE DLL STRATEGY
• 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
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”).
Thread-Safe DLL with a State Structure
CHAPTER 12 NETWORK PROGRAMMING WITH WINDOWS SOCKETS