Some Pending cosmetics and small fixes
[nobug.git] / src / nobug_thread.c
blob9964877520ead81f5c71ea52b823d58a60e505e0
1 /*
2 This file is part of the NoBug debugging library.
4 Copyright (C)
5 2007, 2008, 2009, 2010, Christian Thaeter <ct@pipapo.org>
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, contact Christian Thaeter <ct@pipapo.org>.
20 #define NOBUG_LIBNOBUG_C
21 #include "nobug.h"
22 #include "llist.h"
24 pthread_mutex_t nobug_logging_mutex = PTHREAD_MUTEX_INITIALIZER;
28 thread id handling
30 pthread_key_t nobug_tls_key;
31 static unsigned nobug_thread_cnt = 0;
33 struct nobug_tls_data*
34 nobug_thread_set (const char* name)
36 struct nobug_tls_data * tls = pthread_getspecific (nobug_tls_key);
37 if (!tls)
39 tls = malloc (sizeof *tls);
40 if (!tls) abort();
41 tls->thread_num = ++nobug_thread_cnt;
42 tls->thread_gen = 0;
43 tls->data = NULL;
44 pthread_setspecific (nobug_tls_key, tls);
46 else
48 if (!llist_is_empty(&tls->res_stack))
50 nobug_log (&nobug_flag_NOBUG_ON, LOG_EMERG, "NOBUG",
51 (const struct nobug_context){"-", 0, "nobug_thread_set"},
52 " changing thread_id while resources are in use");
53 abort();
55 free ((char*)tls->thread_id);
56 ++tls->thread_gen;
59 char buf[256];
60 snprintf (buf, 256, "%s_%d", name, tls->thread_num);
61 tls->thread_id = strdup(buf);
62 if (!tls->thread_id)
64 nobug_log (&nobug_flag_NOBUG_ON, LOG_EMERG, "NOBUG",
65 (const struct nobug_context){"-", 0, "nobug_thread_set"},
66 " failed thread id allocation");
67 abort();
70 llist_init (&tls->res_stack);
72 return tls;
76 struct nobug_tls_data*
77 nobug_thread_get (void)
79 struct nobug_tls_data* tls = pthread_getspecific (nobug_tls_key);
80 if (!tls)
81 return nobug_thread_set ("thread");
83 return tls;
87 const char*
88 nobug_thread_id_set (const char* name)
90 return nobug_thread_set (name) -> thread_id;
94 const char*
95 nobug_thread_id_get (void)
97 return nobug_thread_get () -> thread_id;
101 void**
102 nobug_thread_data (void)
104 return &nobug_thread_get () -> data;