vendredi 9 août 2019

Using thread_local in header only properly

I am trying to use thread local in a class that is header only. My current implementation:

class outer{
  class ctx{ /*stuff here*/ }

  static inline ctx* _ctx(ctx* nctx=(ctx*)1){
      static thread_local ctx* x{nullptr};
      if(nctx!=(ctx*)1) x=nctx;
      return x;
  }
}

example usage :

static ctx* _register(){
    ctx* mctx = _ctx();
    if(mctx) return mctx;
    //std::lock_guard<std::mutex> guard(_gctx().g_mutex);
    boost::unique_lock< boost::shared_mutex > lock(_gctx().g_mutex);
    mctx = _ctx(new ctx());
    _gctx().g_ctxes.push_back(mctx);
    return mctx;
}

3 questions in one :

1) is this hackaround safe ?

2) will the if(nctx!=(ctx*)1) x=nctx; get optimised out in inlines

3) is there a better way to achieve this (and general static field initialization without .cpp)

Aucun commentaire:

Enregistrer un commentaire