前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Apache Thrift的C++多线程编程定式

Apache Thrift的C++多线程编程定式

作者头像
一见
发布2019-03-20 10:52:08
7100
发布2019-03-20 10:52:08
举报
文章被收录于专栏:蓝天蓝天

Facebook贡献给Apache的开源RPC组件Thrift有着广泛的应用,C++中使用Thrift也十分普遍,但由于Thrift的Handler会被多个线程调用,因而多线程中应用并不直接的友好,利用C++的“thread_local”特性或GCC的“__thread”特性可化简这一问题。

看具体实例,有一Thrift?service:XService,编译后生成接口文件XServiceIf,接口的实例类为XHandler:

代码语言:javascript
复制
class?XHandler:?public?XService
{
};

由于XHandler会被多个线程调用,直接使用起来需要加锁,不是那么方便。为此引入线程级类XHelper:

代码语言:javascript
复制
class?XHelper
{
};

XHanlder不做具体的实现,全部委托给XHelper,把XHelper定义为线程级变量:

代码语言:javascript
复制
//?stg:?Static?Thread?Global
#if?__cplusplus?<?201103L
static?__thread?XHelper*?stg_xhelper;
#else
static?thread_local?XHelper*?stg_xhelper;
#endif?//?__cplusplus?<?201103L

新的实现就完全不用关心多线程了:

代码语言:javascript
复制
static?bool?init_xhelper()?{
if?(NULL?==?stg_xhelper)?{
stg_xhelper?=?new?XHelper;
if?(!stg_xhelper->init())?{
delete?stg_xhelper;
stg_xhelper?=?NULL;
}
}
return?stg_xhelper?!=?NULL;
}
void?XHandler::foo()?{
if?(init_xhelper())?{
stg_xhelper->foo();
}
}
void?XHelper::foo()?{
}
本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com