How to make setlocale take effect on threads?
To make the locale setting effective in a program, you can use the function std::setlocale() in the thread. Below is an example code:
#include <iostream>
#include <thread>
#include <locale>
void threadFunction()
{
std::setlocale(LC_ALL, ""); // 设置locale
std::cout.imbue(std::locale()); // 应用locale到输出流
std::cout << "线程中的locale设置生效了!" << std::endl;
}
int main()
{
std::thread t(threadFunction);
t.join();
std::cout << "主线程中的locale设置没有生效!" << std::endl;
return 0;
}
In this example code, the threadFunction() function is executed in a new thread. Inside this function, we first call std::setlocale(LC_ALL, “”) to set the locale, and then use std::cout.imbue(std::locale()) to apply the locale to the output stream. This way, the output in the thread will be formatted according to the set locale.
Please note that the std::setlocale() function is not reentrant in a multi-threaded environment and may lead to race conditions. Therefore, caution should be taken when using std::setlocale() in a multi-threaded program.