]> mj.ucw.cz Git - libucw.git/blobdiff - lib/threads.c
gettid: fixed a compilation bug on gentoo
[libucw.git] / lib / threads.c
index f45c8e38a95a36bf8de359e32e526748e2192283..c7497f95247f5dc2d6205d1d080686d1ad02b30f 100644 (file)
 
 #include <pthread.h>
 
+#ifdef CONFIG_LINUX
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#ifdef __NR_gettid
+static pid_t
+gettid(void)
+{
+  return syscall(__NR_gettid);
+}
+#define CONFIG_USE_GETTID
+#endif
+#endif
+
 static pthread_key_t ucwlib_context_key;
 static pthread_mutex_t ucwlib_master_mutex;
 
@@ -31,6 +45,25 @@ ucwlib_threads_init(void)
   pthread_mutex_init(&ucwlib_master_mutex, NULL);
 }
 
+static int
+ucwlib_tid(void)
+{
+  static int tid_counter;
+  int tid;
+
+#ifdef CONFIG_USE_GETTID
+  tid = gettid();
+  if (tid > 0)
+    return tid;
+  /* The syscall might be unimplemented */
+#endif
+
+  ucwlib_lock();
+  tid = ++tid_counter;
+  ucwlib_unlock();
+  return tid;
+}
+
 struct ucwlib_context *
 ucwlib_thread_context(void)
 {
@@ -38,6 +71,7 @@ ucwlib_thread_context(void)
   if (!c)
     {
       c = xmalloc_zero(sizeof(*c));
+      c->thread_id = ucwlib_tid();
       pthread_setspecific(ucwlib_context_key, c);
     }
   return c;
@@ -58,7 +92,7 @@ ucwlib_unlock(void)
 #else
 
 struct ucwlib_context *
-ucw_thread_context(void)
+ucwlib_thread_context(void)
 {
   static struct ucwlib_context ucwlib_context;
   return &ucwlib_context;
@@ -82,7 +116,7 @@ int main(void)
 {
   ucwlib_lock();
   ucwlib_unlock();
-  ucwlib_thread_context();
+  log(L_INFO, "tid=%d", ucwlib_thread_context()->thread_id);
   return 0;
 }