]> mj.ucw.cz Git - libucw.git/blobdiff - lib/threads.c
Merge with git+ssh://cvs.ucw.cz/projects/sherlock/GIT/sherlock.git
[libucw.git] / lib / threads.c
index 26033e54d8fb49c54b84a8b1d1d50f66b192e03f..d2e0f220d769bce15c34935cb12ca259e8413cfe 100644 (file)
 
 #include <pthread.h>
 
 
 #include <pthread.h>
 
+#ifdef CONFIG_LINUX
+#include <sys/types.h>
+#include <linux/unistd.h>
+#ifdef __NR_gettid
+static _syscall0(pid_t, gettid)
+#define CONFIG_USE_GETTID
+#endif
+#endif
+
 static pthread_key_t ucwlib_context_key;
 static pthread_mutex_t ucwlib_master_mutex;
 
 static pthread_key_t ucwlib_context_key;
 static pthread_mutex_t ucwlib_master_mutex;
 
+static void
+ucwlib_free_thread_context(void *p)
+{
+  xfree(p);
+}
+
 static void CONSTRUCTOR
 ucwlib_threads_init(void)
 {
 static void CONSTRUCTOR
 ucwlib_threads_init(void)
 {
-  if (pthread_key_create(&ucwlib_context_key, NULL) < 0)
+  if (pthread_key_create(&ucwlib_context_key, ucwlib_free_thread_context) < 0)
     die("Cannot create pthread_key: %m");
   pthread_mutex_init(&ucwlib_master_mutex, NULL);
 }
 
     die("Cannot create pthread_key: %m");
   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)
 {
 struct ucwlib_context *
 ucwlib_thread_context(void)
 {
@@ -32,6 +66,7 @@ ucwlib_thread_context(void)
   if (!c)
     {
       c = xmalloc_zero(sizeof(*c));
   if (!c)
     {
       c = xmalloc_zero(sizeof(*c));
+      c->thread_id = ucwlib_tid();
       pthread_setspecific(ucwlib_context_key, c);
     }
   return c;
       pthread_setspecific(ucwlib_context_key, c);
     }
   return c;
@@ -52,7 +87,7 @@ ucwlib_unlock(void)
 #else
 
 struct ucwlib_context *
 #else
 
 struct ucwlib_context *
-ucw_thread_context(void)
+ucwlib_thread_context(void)
 {
   static struct ucwlib_context ucwlib_context;
   return &ucwlib_context;
 {
   static struct ucwlib_context ucwlib_context;
   return &ucwlib_context;
@@ -76,7 +111,7 @@ int main(void)
 {
   ucwlib_lock();
   ucwlib_unlock();
 {
   ucwlib_lock();
   ucwlib_unlock();
-  ucwlib_thread_context();
+  log(L_INFO, "tid=%d", ucwlib_thread_context()->thread_id);
   return 0;
 }
 
   return 0;
 }