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;

    }

       

posted @ 2014-10-10 19:18  阁子  阅读(549)  评论(0编辑  收藏  举报