zoukankan      html  css  js  c++  java
  • c++11中的static

    • 超赞的线程安全的初始化

      static plsa::PLSAModel& model()

      {

      static plsa::PLSAModel _model = ([&]() {

      plsa::PLSAModel _model;

      string modelPath = "./data/plsa.model/pzw.idx";

      PSCONF(modelPath, "PlsaTopic");

      _model.Load(modelPath);

      return _model;

      })();

      return _model;

      }

         

      这个代码是线程安全的,c++11保证初始化构造或者赋值函数只被调用一次!

         

    • 更赞的thread local

      线程内部的global变量,让代码变得更简洁,比如我有一个分词器,词典数据是global的全局唯一可读可以弄成

      static变量, 每个线程内部需要一个buffer放切分数据,这样线程安全同时线程内部不需要反复开辟这空间,速度最优,那么这个buffer可以用thread local

      static bool Init(int seg_buff_size = SegHandle::SEG_BUFF_SIZE, string data_dir = "./data/wordseg", int type = SEG_USE_DEFAULT, string conf_path = "./conf/scw.conf")

      {

      //only once init 静态词典数据 static 初始化

      static bool ret = init(data_dir.c_str(), type, conf_path.c_str());

         

      if (!ret)

      {

      return false;

      }

         

      //only once init for each thread 分词内部线程内部buffer数据 thread local

      static thread_local bool isHandleInited = false;

      if (!isHandleInited)

      {

      handle().init(seg_buff_size);

      isHandleInited = true;

      }

         

      return ret;

      }

         

      static SegHandle& handle()

      {

      static thread_local SegHandle _handle;

      return _handle;

      }

         

  • 相关阅读:
    Codeforces Round #647 (Div. 2) A
    Acwing 1129. 热浪 解题报告
    二分 + 三分模板
    可持久化线段树(主席树)模板
    《架构之美》-----阅读笔记四
    《架构之美》-----阅读笔记三
    《架构之美》-----阅读笔记二
    《架构之美》-----阅读笔记一
    《软件需求》------阅读笔记三
    《软件需求》------阅读笔记二
  • 原文地址:https://www.cnblogs.com/rocketfan/p/4017607.html
Copyright © 2011-2022 走看看