I am actually failing to find an answer to this question in boost documentation. I am being a bit paranoid about using atof
in a multi-threaded environment, so one suggestion was to replace the call with lexical_cast
. Is lexical_cast
thread-safe?
Yes, boost::lexical_cast
does not modify the input string in any way and produces a new output if run on the same string from multiple threads.
It creates a stringstream
which in itself is not thread-safe, ie cannot be shared between threads without synchronisation, but would use a different stringstream
object in each thread.
The issue I have with lexical_cast
which is why I avoid using it is the total uselessness of the exception it throws (bad_cast with no context). However that is a separate issue, not thread-safety.
Another issue (limitation) with lexical_cast is that it will only use the C locale (classic). So if you have your own facet, maybe for date-times, and you want to use lexical_cast on it, you may be tempted to modify the classic locale as a workaround, and that is where it will stop being thread-safe unless it is done right at the start.
In reality, if you are parsing a file you would probably be better off using either boost::spirit
if it has a specific grammar or boost::serialize
or even regular istream. In fact boost::lexical_cast
would be highly inefficient for this purpose as it creates a new stream for every token.
Concurrent calls to lexical_cast
are safe. But pay attention that it depends on (at least for my installed version of Boost) the currently installed C++ locale. Access to the installed C++ (as well as C) locale should be synchronized manually by the user. See the Data races section here . So, for example, concurrent calls to lexical_cast
and std::locale::global
are unsafe. Despite this, it is considered bad practice to change the installed C/C++ locale other than at program startup.
It doesn't mention anything about thread safety in the docs for it, so the safe thing to assume is that it isn't. I found this mailing list that seems to support this notion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.