diff --git a/trunk/src/protocol/srs_service_log.cpp b/trunk/src/protocol/srs_service_log.cpp index 5dafb4c05..2b4af2f27 100644 --- a/trunk/src/protocol/srs_service_log.cpp +++ b/trunk/src/protocol/srs_service_log.cpp @@ -49,32 +49,50 @@ SrsContextId SrsThreadContext::generate_id() return cid.set_value(srs_random_str(8)); } +static SrsContextId _srs_context_default; +static int _srs_context_key = -1; +void _srs_context_destructor(void* arg) +{ + SrsContextId* cid = (SrsContextId*)arg; + srs_freep(cid); +} + const SrsContextId& SrsThreadContext::get_id() { - return cache[srs_thread_self()]; + if (!srs_thread_self()) { + return _srs_context_default; + } + + void* cid = srs_thread_getspecific(_srs_context_key); + if (!cid) { + return _srs_context_default; + } + + return *(SrsContextId*)cid; } const SrsContextId& SrsThreadContext::set_id(const SrsContextId& v) { - srs_thread_t self = srs_thread_self(); - - if (cache.find(self) == cache.end()) { - cache[self] = v; + if (!srs_thread_self()) { + _srs_context_default = v; return v; } - const SrsContextId& ov = cache[self]; - cache[self] = v; - return ov; + SrsContextId* cid = v.copy(); + + if (_srs_context_key < 0) { + int r0 = srs_key_create(&_srs_context_key, _srs_context_destructor); + srs_assert(r0 == 0); + } + + int r0 = srs_thread_setspecific(_srs_context_key, cid); + srs_assert(r0 == 0); + + return v; } void SrsThreadContext::clear_cid() { - srs_thread_t self = srs_thread_self(); - std::map::iterator it = cache.find(self); - if (it != cache.end()) { - cache.erase(it); - } } impl_SrsContextRestore::impl_SrsContextRestore(SrsContextId cid) diff --git a/trunk/src/protocol/srs_service_st.cpp b/trunk/src/protocol/srs_service_st.cpp index 0e2c4f586..743ee049f 100644 --- a/trunk/src/protocol/srs_service_st.cpp +++ b/trunk/src/protocol/srs_service_st.cpp @@ -381,6 +381,21 @@ int srs_mutex_unlock(srs_mutex_t mutex) return st_mutex_unlock((st_mutex_t)mutex); } +int srs_key_create(int *keyp, void (*destructor)(void *)) +{ + return st_key_create(keyp, destructor); +} + +int srs_thread_setspecific(int key, void *value) +{ + return st_thread_setspecific(key, value); +} + +void *srs_thread_getspecific(int key) +{ + return st_thread_getspecific(key); +} + int srs_netfd_fileno(srs_netfd_t stfd) { return st_netfd_fileno((st_netfd_t)stfd); diff --git a/trunk/src/protocol/srs_service_st.hpp b/trunk/src/protocol/srs_service_st.hpp index ed86737d6..4ae72c8bc 100644 --- a/trunk/src/protocol/srs_service_st.hpp +++ b/trunk/src/protocol/srs_service_st.hpp @@ -81,6 +81,10 @@ extern int srs_mutex_destroy(srs_mutex_t mutex); extern int srs_mutex_lock(srs_mutex_t mutex); extern int srs_mutex_unlock(srs_mutex_t mutex); +extern int srs_key_create(int* keyp, void (*destructor)(void*)); +extern int srs_thread_setspecific(int key, void* value); +extern void* srs_thread_getspecific(int key); + extern int srs_netfd_fileno(srs_netfd_t stfd); extern int srs_usleep(srs_utime_t usecs);