在多线程的环境下,有时候我们不需要某函数被调用多次或者某些变量被初始化多次,它们仅仅只需要被调用一次或者初始化一次即可。很多时候我们为了初始化某些数据会写出如下代码,这些代码在单线程中是没有任何问题的,但是在多线程中就会出现不可预知的问题。
bool initialized = false; // global flag
if (!initialized) {
// initialize if not initialized yet
initialize ();
initialized = true;
}
or
static std::vector<std::string> staticData;
void foo ()
{
if (staticData.empty ()) {
staticData = initializeStaticData ();
}
...
}
为了解决上述多线程中出现的资源竞争导致的数据不一致问题,我们大多数的处理方法就是使用互斥锁来处理。
在传统的多线程中一般只初始化一次,或者调用一次可以如下处理:
bool m_binit = false;
void initdata()
{
if (!m_binit)
{
m_binit = true;
cout << "我在初始化\n";
}
else
{
cout << "我已经初始化了\n";
}
}
std::mutex m_tex;
void thread1()
{
cout << "thread1:\n";
m_tex.lock();
initdata();
m_tex.unlock();
}
void thread2()
{
cout << "thread2:\n";
m_tex.lock();
initdata();
m_tex.unlock();
}
void main()
{
std::thread t1(thread1);
std::thread t2(thread2);
t1.detach();
t2.detach();
system("pause");
}
结果:

从结果可以看出,之初始化了一次。
在c++11中使用std::call_once函数来处理,其定义如下头文件#include<mutex>
具体使用如下:
std::once_flag flagx;//1.定义一个静态变量
void thread1()
{
cout << "thread1 start:\n";
//2.调用call_once
std::call_once(flagx, [](){
//初始化
initdata();
});
}
void thread2()
{
cout << "thread2 start:\n";
std::call_once(flagx, [](){
//初始化
initdata();
});
}
void main()
{
std::thread t1(thread1);
std::thread t2(thread2);
t1.detach();
t2.detach();
system("pause");
}
结果:

从结果可以看出,确实只初始化了一次,两者相比后者简洁,值得推介。

本文探讨了在多线程环境中如何确保函数仅被调用一次或变量仅被初始化一次的方法。通过使用互斥锁和C++11中的`std::call_once`函数来解决资源竞争问题,实现数据的一致性。
1117

被折叠的 条评论
为什么被折叠?



