首页 > 学院 > 开发设计 > 正文

Boost ptree 解析json字符串 多线程下程序crash

2019-11-06 07:21:38
字体:
来源:转载
供稿:网友

今天一个service即将发布之前,用压力测试试了一下,很快就segmentation fault,吓了一身冷汗。

三小时候确定是因为最近几天引入boost::ptree来将解析json的时候出问题。重新自己实现解析代码后,问题解决。

单独开一个工程,在多线程的情况下调用,错误重现。下面的代码时不时就会crash。

[cpp] view plaincopyPRint?class testBind {  public:      void testFunc() {          cout<<"ok"<<endl;          string str = "{/"51/":1,/"50/":1}";          stringstream stream;          stream<<str;          ptree tree;          read_json(stream, tree);      }  };  /*  *   */  int main(int argc, char** argv) {      testBind tb;      boost::thread_group tg;      for (int i = 0; i < 20; ++i) {          tg.add_thread(new boost::thread(boost::bind(&testBind::testFunc, &tb)));      }      int x;      cin >> x;        tg.join_all();          return 0;  }  

补充:因为ptree 下层使用的 spirit 库默认不是线程安全的 。需要在使用 include spirit 头文件的时候使用 宏 

#define BOOST_SPIRIT_THREADSAFE 。 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表