char* randomStrGen(int length)
{
static int inc = 2;
inc++;
srand((unsigned)GetTickCount() % 10000* (inc+inc));
static std::string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
std::string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
char* Cresult=(char*)malloc(result.size()+1);
strcpy(Cresult, result.c_str());
return Cresult;
}
我做了一个生成随机字符串的算法,但是无论我多么努力地尝试多次连续调用(在我的情况下,创建了2个线程并调用它们),都会生成相同的字符串。为什么,因为我添加了一个数字为每个调用添加唯一性的 srand 初始化程序,事实上,对于每个调用,srand 必须使用不同的数字进行初始化。
尝试更换
在
或者干脆去掉不必要的调用
srand,主要播一次就够了。