C++(11):原子类型

322 篇文章 3 订阅 ¥199.90 ¥99.00

为了便于多线程编程,C++11引入了原子类型,可以保证对该类型变量的操作不会产生多线程的竞争:

#include <iostream>
#include <atomic>
#include <thread>
using namespace std;

atomic_int g_d{0};    //定义原子类型变量

void tFunc(int a)
{
	for(int i = 0; i < 100000000; ++i)
	{
		g_d++;        //对原子类型的操作,不会产生竞争
	}
}

int main(){
	thread t1(tFunc, 0);
	thread t2(tFunc, 0);
	t1.join();
	t2.join();
	cout<<g_d<<endl;
	return 0;
}

运行程序输出:
200000000

可用类型,参考官方文档:

Standard library header <atomic> (C++11) - cppreference.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++中的原子类型是一种线程安全的类型,它可以保证多个线程同时访问时的正确性。原子类型在并发编程中非常重要,因为多个线程同时访问同一个变量时,可能会导致竞态条件(race condition)的问题,而原子类型可以避免这种问题的发生。 在C++11标准中,提供了以下原子类型: - std::atomic_bool - std::atomic_char - std::atomic_schar - std::atomic_uchar - std::atomic_short - std::atomic_ushort - std::atomic_int - std::atomic_uint - std::atomic_long - std::atomic_ulong - std::atomic_llong - std::atomic_ullong - std::atomic_char16_t - std::atomic_char32_t - std::atomic_wchar_t - std::atomic_int_least8_t - std::atomic_uint_least8_t - std::atomic_int_least16_t - std::atomic_uint_least16_t - std::atomic_int_least32_t - std::atomic_uint_least32_t - std::atomic_int_least64_t - std::atomic_uint_least64_t - std::atomic_int_fast8_t - std::atomic_uint_fast8_t - std::atomic_int_fast16_t - std::atomic_uint_fast16_t - std::atomic_int_fast32_t - std::atomic_uint_fast32_t - std::atomic_int_fast64_t - std::atomic_uint_fast64_t - std::atomic_size_t - std::atomic_ptrdiff_t - std::atomic_intmax_t - std::atomic_uintmax_t 使用原子类型时,可以通过std::atomic<>模板来定义一个原子类型的变量,例如: ```c++ std::atomic<int> my_atomic_var; ``` 原子类型提供了以下操作方法: - store:设置原子变量的值 - load:获取原子变量的值 - exchange:交换原子变量的值 - compare_exchange_strong:比较并交换原子变量的值(强保证) - compare_exchange_weak:比较并交换原子变量的值(弱保证) - fetch_add:原子地将原子变量的值加上指定值 - fetch_sub:原子地将原子变量的值减去指定值 - fetch_and:原子地将原子变量的值与指定值按位与 - fetch_or:原子地将原子变量的值与指定值按位或 - fetch_xor:原子地将原子变量的值与指定值按位异或 这些操作方法可以保证多个线程同时访问同一个原子变量时的正确性。例如,使用原子变量来实现一个计数器: ```c++ #include <atomic> #include <iostream> #include <thread> std::atomic<int> counter(0); void increment_counter() { for (int i = 0; i < 100000; i++) { counter++; } } int main() { std::thread t1(increment_counter); std::thread t2(increment_counter); t1.join(); t2.join(); std::cout << "Counter value: " << counter << std::endl; return 0; } ``` 在上面的代码中,我们定义了一个原子变量counter,并使用两个线程分别对其进行了100000次自增操作。由于原子变量的自增操作是线程安全的,因此我们可以保证最终计数器的值是正确的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

风静如云

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

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

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

打赏作者

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

抵扣说明:

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

余额充值