您的位置:首页 > 其它

关于boost库性能与安全的一些总结

2017-03-08 19:48 645 查看
最近工作上遇到几个问题都与boost库有关,所以做一下简单的总结。

1.多线程环境使用boost库引起的crash

项目中使用到boost::filesystem::is_regular_file来做判断,但是在多线程环境下出现了crash,查看原因是在boost库中进行窄字符串与宽字符串转换的时候,进入到一个静态函数中,但是静态函数没有加锁,所以导致在第一个线程修改结束之前第二个线程没有等待就直接使用了指针,使用空指针导致crash。

boost::filesystem::path 类型在多线程环境下要谨慎使用。

boost库的bug track:https://svn.boost.org/trac/boost/ticket/6320

const path::codecvt_type *& path::wchar_t_codecvt_facet() {

static const std::codecvt<wchar_t, char, std::mbstate_t> *

facet(

&std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t> >

(path_locale()));

return facet;

}

This method is entered by multiple threads concurrently and the static pointer "facet" gets initialized by the first thread (which takes some time) but the other threads don't wait and just continue while facet is a NULL pointer.

In boost 1.44 this crash didn't occur. It seems that the initialization of global variable const fs::path dot_path(L"."); in filesystem/v3/source/path.cpp resulted in a call of path::wchar_t_codecvt_facet(), so the static "facet" pointer got initialized during
program startup while no other threads were running.

In boost 1.48 the initialization of the same globale variable doesn't result in a call of path::wchar_t_codecvt_facet() so race conditions might occur during initialization of the static "facet" pointer (in C++ 03).

2.boost库的性能问题

Boost库在性能上并没有做的那么完美,在进行字符串查找的时候,boost库提供了一个boost::contains和boost::icontains方法,后者忽略字符串大小写。但是在测试性能的时候,这两个函数对性能影响巨大,使用string/wstring自带的find函数,性能会提高不少。boost::icontain耗性能的主要原因查看了源码,发现主要是在内部做了多次is_equal()的调用,且每次is_equal时都会进行to_upper()或者to_lower()一类的操作。所以非常考虑性能的话建议使用string自带的find。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: