线程安全的随机数

      最后更新:2022-08-03 15:16:28 手机定位技术交流文章

      Microsoft .NET Framework 内部实现的随机数算法重复率很低,但这还意味着你需要消耗更多的CPU,如果一个相同随机对象的实例在线程上持续存在,这就导致了涉及随机数字的死循环,C/C++本身从.NET框架摘要 C#翻译成C++实现也可以控制自己来防止死亡循环,但是用C#直接使用这个对象是危险的,当然,一个单一的随机例子不会重复很多,你不会陷入一个死循环。

      int server_random_r(volatile unsigned int* seed) {
      unsigned int next = *seed;
      int result;

      next *= 1103515245;
      next += 12345;
      result = (unsigned int)(next / 65536) % 2048;

      next *= 1103515245;
      next += 12345;
      result <<= 10;
      result ^= (unsigned int)(next / 65536) % 1024;

      next *= 1103515245;
      next += 12345;
      result <<= 10;
      result ^= (unsigned int)(next / 65536) % 1024;

      *seed = next;
      return result;
      }

      int server_random(int min, int max) {
      static volatile unsigned int seed = time(NULL);

      int v = server_random_r(&seed);
      return v % (max - min + 1) + min;
      }

      int server_random_ascii() {
      static Byte x_[] = { 'a', 'A', '0' };
      static Byte y_[] = { 'z', 'Z', '9' };

      int i_ = server_random() % 3;
      return server_random(x_[i_], y_[i_]);
      }

      本文由 在线网速测试 整理编辑,转载请注明出处,原文链接:https://www.wangsu123.cn/news/31422.html

          热门文章

          文章分类