Due to the unpredictable of racing situation of multiple symmetric threads, is it good to use this uncertainty to build a uniform random generator?
For example, the codes from http://ift.tt/1CztJjq , call it twice to generate an random integer in [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;
}
And call the code (from http://ift.tt/1XLIImA) certain times for a request length of random bits.
#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;
}
Is that real uniform and with no period? The sequence is unable to reproduce, that may be a weak for debugging.
Aucun commentaire:
Enregistrer un commentaire