Sfoglia il codice sorgente

Add hthread_setname hthread_getname

ithewei 4 anni fa
parent
commit
d486bf86b8
2 ha cambiato i file con 42 aggiunte e 0 eliminazioni
  1. 20 0
      base/hthread.c
  2. 22 0
      base/hthread.h

+ 20 - 0
base/hthread.c

@@ -0,0 +1,20 @@
+#include "hthread.h"
+
+static hthread_key_t tls_thread_name = INVALID_HTHREAD_KEY;
+
+void hthread_setname(const char* name) {
+    if (tls_thread_name == INVALID_HTHREAD_KEY) {
+        hthread_key_create(&tls_thread_name);
+    }
+    hthread_set_value(tls_thread_name, name);
+}
+
+const char* hthread_getname() {
+    static char unnamed[32];
+    void* value = hthread_get_value(tls_thread_name);
+    if (value) {
+        return (char*)value;
+    }
+    snprintf(unnamed, sizeof(unnamed)-1, "thread-%ld", hv_gettid());
+    return unnamed;
+}

+ 22 - 0
base/hthread.h

@@ -1,6 +1,7 @@
 #ifndef HV_THREAD_H_
 #define HV_THREAD_H_
 
+#include "hexport.h"
 #include "hplatform.h"
 
 #ifdef OS_WIN
@@ -59,6 +60,14 @@ static inline int hthread_join(hthread_t th) {
     CloseHandle(th);
     return 0;
 }
+
+#define hthread_key_t               DWORD
+#define INVALID_HTHREAD_KEY         0xFFFFFFFF
+#define hthread_key_create(pkey)    *pkey = TlsAlloc()
+#define hthread_key_delete          TlsFree
+#define hthread_get_value           TlsGetValue
+#define hthread_set_value           TlsSetValue
+
 #else
 typedef pthread_t   hthread_t;
 typedef void* (*hthread_routine)(void*);
@@ -73,8 +82,21 @@ static inline hthread_t hthread_create(hthread_routine fn, void* userdata) {
 static inline int hthread_join(hthread_t th) {
     return pthread_join(th, NULL);
 }
+
+#define hthread_key_t               pthread_key_t
+#define INVALID_HTHREAD_KEY         0xFFFFFFFF
+#define hthread_key_create(pkey)    pthread_key_create(pkey, NULL)
+#define hthread_key_delete          pthread_key_delete
+#define hthread_get_value           pthread_getspecific
+#define hthread_set_value           pthread_setspecific
+
 #endif
 
+BEGIN_EXTERN_C
+HV_EXPORT void hthread_setname(const char* name);
+HV_EXPORT const char* hthread_getname();
+END_EXTERN_C
+
 #ifdef __cplusplus
 /************************************************
  * HThread