Jahid
Jahid

Reputation: 22438

Thread safe approach to setlocale()

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

Upvotes: 1

Views: 1182

Answers (1)

James Hurford
James Hurford

Reputation: 2058

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.

Upvotes: 2

Related Questions