为什么比赛条件的输出不是随机的

Why is the output from race conditions not random?

本文关键字:随机 输出 为什么 条件      更新时间:2024-09-23

我设置了以下竞赛条件来生成一些随机位。然而,据我所知,输出不是随机的。我想知道为什么(为了学习(。这是我的代码:

#include <iostream>
#include <vector>
#include <atomic>
#include <thread>
#include <cmath>
using namespace std;
void compute_entropy(const vector<bool> &randoms) {
int n0 = 0, n1 = 0;
for(bool x: randoms) {
if(!x) n0++;
else n1++;
}
double f0 = n0 / ((double)n0 + n1), f1 = n1 / ((double)n0 + n1);
double entropy = - f0 * log2(f0) - f1 * log2(f1);
for(int i = 0; i < min((int)randoms.size(), 100); ++i)
cout << randoms[i];
cout << endl;
cout << endl;
cout << f0 << " " << f1 << " " << endl;
cout << entropy << endl;
return;
}
int main() {
const int N = 1e7;
bool x = false;
atomic<bool> finish1(false), finish2(false);
vector<bool> randoms;
thread t1([&]() {
for(int i = 0; !finish1; ++i)
x = false;
});
thread t2([&]() {
for(int i = 0; !finish2; ++i)
x = true;
});
thread t3([&]() {
for(int i = 0; i < N; ++i)
randoms.push_back(x);
finish1 = finish2 = true;
});
t3.join();
t1.join();
t2.join();
compute_entropy(randoms);
return 0;
}

我这样编译和运行它:

$ g++ -std=c++14 threads.cpp -o threads -lpthread
$ ./threads 
0101001011000111110100101101111101100100010001111000111110001001010100011101110011011000010100001110
0.473792 0.526208 
0.998017

无论我运行了多少次,结果都是扭曲的。

对于1000万个数字,正确的随机数生成器的结果正如人们所期望的那样:

>>> np.mean(np.random.randint(0, 2, int(1e7)))
0.5003456
>>> np.mean(np.random.randint(0, 2, int(1e7)))
0.4997095

为什么比赛条件的输出不是随机的?

不能保证竞争条件会产生随机输出。它不能保证是纯随机的,甚至不能保证是任何质量的伪随机的。

据我所知,输出不是随机的。

没有任何测试可以肯定地否定随机性。

有些测试可以表明,序列可能不包含某些特定模式,因此通过多次此类测试的序列可能是随机的。然而,据我所知,你还没有进行过这样的测试。你似乎在衡量输出的分布是否均匀——这是一个独立于随机性的特性。因此,你得出的输出不是随机的结论并不是基于相关的测量。


此外,您的程序还有数据竞赛。因此,整个程序的行为是未定义的,这里不能保证程序的行为会像人们合理预期的那样。