1 /* $NetBSD: mtctxres.c,v 1.4 2007/03/30 20:40:52 ghen Exp $ */
3 #include <port_before.h>
11 #include <resolv_mt.h>
12 #include <port_after.h>
15 static pthread_key_t key
;
16 static int mt_key_initialized
= 0;
18 static int __res_init_ctx(void);
19 static void __res_destroy_ctx(void *);
21 #if defined(sun) && !defined(__GNUC__)
22 #pragma init (_mtctxres_init)
26 static mtctxres_t sharedctx
;
30 * Initialize the TSD key. By doing this at library load time, we're
31 * implicitly running without interference from other threads, so there's
32 * no need for locking.
35 _mtctxres_init(void) {
36 int pthread_keycreate_ret
;
38 pthread_keycreate_ret
= pthread_key_create(&key
, __res_destroy_ctx
);
39 if (pthread_keycreate_ret
== 0)
40 mt_key_initialized
= 1;
45 * To support binaries that used the private MT-safe interface in
46 * Solaris 8, we still need to provide the __res_enable_mt()
47 * and __res_disable_mt() entry points. They're do-nothing routines.
50 __res_enable_mt(void) {
55 __res_disable_mt(void) {
61 __res_init_ctx(void) {
67 if (pthread_getspecific(key
) != 0) {
72 if ((mt
= malloc(sizeof (mtctxres_t
))) == 0) {
77 memset(mt
, 0, sizeof (mtctxres_t
));
79 if ((ret
= pthread_setspecific(key
, mt
)) != 0) {
89 __res_destroy_ctx(void *value
) {
91 mtctxres_t
*mt
= (mtctxres_t
*)value
;
104 * This if clause should only be executed if we are linking
105 * statically. When linked dynamically _mtctxres_init() should
106 * be called at binding time due the #pragma above.
108 if (!mt_key_initialized
) {
109 static pthread_mutex_t keylock
= PTHREAD_MUTEX_INITIALIZER
;
110 if (pthread_mutex_lock(&keylock
) == 0) {
112 (void) pthread_mutex_unlock(&keylock
);
117 * If we have already been called in this thread return the existing
118 * context. Otherwise recreat a new context and return it. If
119 * that fails return a global context.
121 if (mt_key_initialized
) {
122 if (((mt
= pthread_getspecific(key
)) != 0) ||
123 (__res_init_ctx() == 0 &&
124 (mt
= pthread_getspecific(key
)) != 0)) {