C++ 线程安全随机生成16个字符(含字母、数字和特殊字符)

本文将介绍如何使用 C++ 实现一个线程安全的函数,用于生成包含字母、数字和特殊字符的随机字符串,长度为 16 个字符。

代码实现

#include <iostream>
#include <random>
#include <mutex>
#include <thread>
#include <chrono>

std::mutex mtx;

std::string generateRandomString() {
    std::string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
    std::string result;

    std::lock_guard<std::mutex> lock(mtx); // 加锁

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, chars.length() - 1);

    for (int i = 0; i < 16; ++i) {
        result += chars[dis(gen)];
    }

    return result;
}

void threadFunc() {
    std::string randomString = generateRandomString();
    std::cout << "Random string: " << randomString << std::endl;
}

int main() {
    std::thread t1(threadFunc);
    std::thread t2(threadFunc);

    t1.join();
    t2.join();

    return 0;
}

代码解析

  1. generateRandomString() 函数

    • 该函数使用 std::mutex 对象 mtx 来保证线程安全。
    • 首先定义一个包含字母、数字和特殊字符的字符串 chars。
    • 使用 std::random_device 和 std::mt19937 生成一个随机数生成器。
    • 使用 std::uniform_int_distribution 生成一个随机索引,并通过索引从字符串 chars 中选择一个字符加入到结果字符串 result 中。
    • 最后返回生成的字符串。
  2. threadFunc() 函数

    • 该函数调用 generateRandomString() 函数生成随机字符串并输出到控制台。
  3. main() 函数

    • 创建两个线程来调用 threadFunc() 函数。
    • 使用 join() 方法等待线程执行完毕。

线程安全

代码中使用 std::mutex 对象 mtx 来保证线程安全。在 generateRandomString() 函数中,std::lock_guard<std::mutex> 对象 lock 用于对 mtx 加锁,确保同一时间只有一个线程可以访问函数内部的代码,从而避免多个线程同时修改共享资源 result 字符串导致的数据竞争问题。

总结

本代码实现了使用 C++ 生成线程安全随机字符串的功能,并提供了详细的代码解释和使用示例。希望对您有所帮助。

C++ 线程安全随机生成16个字符(含字母、数字和特殊字符)

原文地址: https://www.cveoy.top/t/topic/p2rs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录