c++之多线程如何初始化变量一次

在多线程的环境下,有时候我们不需要某函数被调用多次或者某些变量被初始化多次,它们仅仅只需要被调用一次或者初始化一次即可。很多时候我们为了初始化某些数据会写出如下代码,这些代码在单线程中是没有任何问题的,但是在多线程中就会出现不可预知的问题。

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");
}

结果:
在这里插入图片描述
从结果可以看出,确实只初始化了一次,两者相比后者简洁,值得推介。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值