You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@brpc.apache.org by GitBox <gi...@apache.org> on 2021/07/02 02:24:22 UTC

[GitHub] [incubator-brpc] wwbmmm commented on issue #1449: bthread: bthread_setspecific may cause memory leak

wwbmmm commented on issue #1449:
URL: https://github.com/apache/incubator-brpc/issues/1449#issuecomment-872665659


   I had encountered this problem before, finally I created a wrapper class that ensure calling bthread_getspecific before bthread_setspecific:
   
   ```cpp
   
   template<typename T>
   class BThreadLocal {
       public:
           BThreadLocal() {
               bthread_key_create(&m_key,
                   [](void* p) {  delete (T*)p; });
           }
   
           T* get() const { 
               return (T*)bthread_getspecific(m_key); 
           }
   
           T* get_or_create() {
               T *p = get();
               if (p == nullptr) {
                   p = new T();
                   set(p);
               }
               return p;
           }
   
           T *operator->() {
               return get_or_create();
           }
   
           T &operator*() {
               return *get_or_create();
           }
   
       private:
           // User can't call set(), that may cause memory leak
           int set(T* p) {
               return bthread_setspecific(m_key, p);
           }
   
           bthread_key_t m_key;
   };
   ```
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@brpc.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@brpc.apache.org
For additional commands, e-mail: dev-help@brpc.apache.org