views:

40

answers:

2

hi, i need to change locale in the thread to parse double with strtod() correctly, i'm using setlocale() for this (C++). is it thread safe? UPD: another problem. when i invoke setlocale() in main function it doesn't effect in other routines deeper. why??? there are a lot of code, so it's problematic to write the chunk.

A: 

You need to consult the documentation for whatever implementation you're using. C++ doesn't currently specify anything about threads so it comes down to the implementation (which you haven't yet told us).

For example, my Linux manpage for setlocale has the snippet:

This string may be allocated in static storage.

which doesn't absolutely indicate that it's thread-unsafe but I'd be very wary. It's likely that calling it with NULL (i.e., querying) would be thread-safe but as soon as you have a thread modifying it, all bets are off.

Probably the safest thing to do (assuming it isn't thread-safe) would be to protect all calls to setlocale with a mutex and have a special function to format your numbers along the lines of:

claim mutex
curr = setlocale to specific value
format number to string
setlocale to curr
release mutex
return string
paxdiablo
a got it, thanks
milo
+1  A: 

For C++98 it depends on the compiler and on which runtime lib you select and on what exactly you mean by thread safe.

E.g. with MSVC and multi-threaded runtime you should be safe in the sense that setlocale itself is. But I don't think you'll get a per-thread locale. Use setlocale for a global locale, not a per-thread locale.

C++98 does not address threading (or, for that matter, dynamic libraries).

Alf P. Steinbach