1

This paper says that setlocale() is thread unsafe. Is there any thread safe approach to set the locale.

I am coding in C++, but the locale will be used by a function from a C library if it makes any difference.

This is basically what I am doing right now:

const char* loc_old = std::setlocale(ltype, 0);
std::setlocale(ltype, mylocale.c_str()); //change the locale
//call some C functions
std::setlocale(ltype, loc_old);          //restore the locale

The solution must be portable and not >=C++11

Jahid
  • 21,542
  • 10
  • 90
  • 108
  • The application global locale, no. You have to instantiate discrete `std::locale` object, and imbue them everywhere, in order to be thread safe. Now that C++ has `thread_local`, what should happen is that there should simply be a default `thread_local` locale, and new execution `std::thread`s inherit one from their parent thread. – Sam Varshavchik Nov 17 '16 at 11:51
  • @SamVarshavchik : unfortunately `thread_local` isn't an option for me.. – Jahid Nov 17 '16 at 12:02

1 Answers1

2

There is a good answer for this here

Is setlocale thread-safe function?

Essentially you, evidently can use

uselocale

As this snippet from one of the answers given to the referenced question suggest

#include <xlocale.h>

locale_t loc = newlocale(LC_ALL_MASK, "nl_NL", NULL);
uselocale(loc);
freelocale(loc)
// Do your thing

There are probably other ways to overcome your problem as well.

Community
  • 1
  • 1
James Hurford
  • 2,018
  • 19
  • 40
  • 1
    Is the `xlocale.h` an standard header? – Jahid Nov 17 '16 at 12:11
  • Probably not. It does seem to be available on Linux, Mac and Windows though. That might not help you if you're writing for micro controllers, etc. The other option is just to use some sort of lock, use setlocale, then restore to previous value, then release the lock. uselocale() just seems easier to use. Locks are the accepted answer on the referenced question I mentioned. – James Hurford Nov 17 '16 at 12:37