std::atomic例子:线程安全的客户端ID生成器

作用

  • std::atomic<uint32_t> 是原子类型,保证多线程环境下的操作安全
  • next_client_id_{1} 初始化为1,作为ID计数器
  • fetch_add(1) 是原子操作:先返回当前值,然后将值加1

代码

#include <iostream>
#include <atomic>
#include <thread>
#include <vector>

class ClientManager {
private:
    std::atomic<uint32_t> next_client_id_{1}; // 客户端ID生成器
    
public:
    uint32_t GenerateClientId() {
        return next_client_id_.fetch_add(1);
    }
};

int main() {
    ClientManager manager;
    
    // 单线程测试
    std::cout << "=== 单线程测试 ===" << std::endl;
    for (int i = 0; i < 5; i++) {
        uint32_t id = manager.GenerateClientId();
        std::cout << "生成的客户端ID: " << id << std::endl;
    }
    
    // 多线程测试
    std::cout << "\n=== 多线程测试 ===" << std::endl;
    std::vector<std::thread> threads;
    
    // 创建5个线程,每个线程生成3个ID
    for (int t = 0; t < 5; t++) {
        threads.emplace_back([&manager, t]() {
            for (int i = 0; i < 3; i++) {
                uint32_t id = manager.GenerateClientId();
                std::cout << "线程" << t << " 生成ID: " << id << std::endl;
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    return 0;
}

多实例:

#include <iostream>
#include <atomic>

class ClientManager {
public:
	ClientManager(){
		client_id = GenerateClientId();
	}
private:
	// 静态原子变量,所有实例共享
	static std::atomic<uint32_t> next_client_id_;
	uint32_t client_id = 0;
public:
	// 生成新的client_id,线程安全
	static uint32_t GenerateClientId() {
		// fetch_add返回的是操作前的值,所以加1后返回的就是新id
		return next_client_id_++;
	}
	
	// 获取当前最新的client_id(非递增)
	uint32_t getClientId() {
		return client_id;
	}
};

// 静态成员变量初始化
std::atomic<uint32_t> ClientManager::next_client_id_{1};

int main() {
	// 不同实例调用生成id
	ClientManager manager1;
	ClientManager manager2;
	ClientManager manager3;
	
	std::cout << "client_id from manager1: " << manager1.getClientId() << std::endl;
	std::cout << "client_id from manager2: " << manager2.getClientId() << std::endl;
	std::cout << "client_id from manager3: " << manager3.getClientId() << std::endl;
	
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿龍1787

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

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

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

打赏作者

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

抵扣说明:

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

余额充值