由於不可預測的多重對稱線程的賽車情況,使用這種不確定性來建立統一的隨機發生器是否好?使用多線程比賽作爲一個隨機數發生器是一個好主意嗎?
例如,從http://www.cplusplus.com/reference/mutex/call_once/的代碼,調用它兩次以在[0,99]中生成一個隨機整數。
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::milliseconds
#include <mutex> // std::call_once, std::once_flag
int winner;
void set_winner (int x) { winner = x; }
std::once_flag winner_flag;
void wait_1000ms (int id) {
// count to 1000, waiting 1ms between increments:
for (int i=0; i<1000; ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// claim to be the winner (only the first such call is executed):
std::call_once (winner_flag,set_winner,id);
}
int main() {
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(wait_1000ms,i+1);
std::cout << "waiting for the first among 10 threads to count 1000 ms...\n";
for (auto& th : threads) th.join();
std::cout << "winner thread: " << winner << '\n';
return 0;
}
然後調用代碼(從http://advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf)某些時間的請求長度爲隨機位。
#include <pthread.h>
#include <stdio.h>
/* Prints x’s to stderr. The parameter is unused. Does not return. */
void* print_xs (void* unused) {
while (1) {
sleep(1);
fputc ('x', stderr);
}
return NULL;
}
int main() {
pthread_t thread_id;
/* Create a new thread. The new thread will run the print_xs function. */
pthread_create (&thread_id, NULL, &print_xs, NULL);
/* Print o’s continuously to stderr. */
while (1) {
sleep(1);
fputc ('o', stderr);
}
return 0;
}
那是真正統一與無期?該序列無法重現,這可能是調試的弱點。