Skip to content

Instantly share code, notes, and snippets.

@vmrob
Created August 14, 2014 20:01
Show Gist options
  • Save vmrob/3ba855501ba029711bf0 to your computer and use it in GitHub Desktop.
Save vmrob/3ba855501ba029711bf0 to your computer and use it in GitHub Desktop.
test
#include <iostream>
#include <thread>
#include <vector>
#include <random>
#define NUM_THREADS 10
#define GOAL 2147000000 // 2147483647 is max
typedef int32_t random_type;
void GenerateInts(uint64_t& iterations, uint64_t seed) {
std::default_random_engine generator(seed);
std::uniform_int_distribution<random_type> distribution(
std::numeric_limits<random_type>::min(),
std::numeric_limits<random_type>::max()
);
random_type num = std::numeric_limits<random_type>::min();
iterations = 0;
while (num < GOAL) {
num = distribution(generator);
++iterations;
}
}
int main() {
std::vector<std::thread> threads;
std::vector<uint64_t> results(NUM_THREADS);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
for (int i = 0; i < NUM_THREADS; ++i) {
threads.push_back(std::thread(std::bind(GenerateInts, std::ref(results[i]), seed + i)));
}
for (int i = 0; i < NUM_THREADS; ++i) {
if (threads[i].joinable()) {
threads[i].join();
}
}
int winner = 0;
int winnerScore = results[0];
for (int i = 1; i < NUM_THREADS; ++i) {
if (results[i] < winnerScore) {
winner = i;
winnerScore = results[i];
}
}
std::cout << "thread " << winner << " wins with a score of " << winnerScore << std::endl;
std::cout << "-------------------" << std::endl;
for (int i = 0; i < NUM_THREADS; ++i) {
std::cout << "thread " << i << ": " << results[i] << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment