From 46094f51969718be31c1c3f7c4b6c9e322d06a8d Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Thu, 30 Aug 2012 09:31:27 -0600 Subject: [PATCH] Added an example of parallel pi. --- Makefile | 4 ++-- pi.cc | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 pi.cc diff --git a/Makefile b/Makefile index ae0e9a2..b1d5aa4 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ CPPFLAGS=-Wall -g -std=c++0x -pthread # CXX=clang++ # CPPFLAGS=-Wall -g -std=c++0x -stdlib=libc++ -L/opt/clang/lib -pthread -all: auto constexpr ilists init init_new lambda loops regex1 regex2 thread thread2 tuple +all: auto constexpr ilists init init_new lambda loops pi regex1 regex2 thread thread2 tuple run: all ./auto @@ -30,7 +30,7 @@ run: all clean: - @rm -vf auto constexpr core* ilists init init_new lambda loops regex1 regex2 thread thread2 tuple + @rm -vf auto constexpr core* ilists init init_new lambda loops pi regex1 regex2 thread thread2 tuple stress: thread2 zsh stress.zsh diff --git a/pi.cc b/pi.cc new file mode 100644 index 0000000..0ae8b70 --- /dev/null +++ b/pi.cc @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include +#include +#include + +static const int num_threads = 8; +static const int max_ = 100000; + +void slice_of_pi(int tries, int my_id, std::atomic & in_circle) { + struct timeval tv; + gettimeofday(&tv, NULL); + srand(tv.tv_usec + my_id); + + std::uniform_int_distribution distribution {0, max_}; + std::mt19937 engine; // Mersenne twister MT19937 + auto generator = std::bind(distribution, engine); + + double x, y, d; + int _in_circle = 0; + for(int i = 0; i < tries; i++) { + x = (float)generator() / (float)max_; + y = (float)generator() / (float)max_; + d = sqrt(x * x + y * y); + if(d < 1.0) + _in_circle++; + } + in_circle += _in_circle; +} + +int main(int argc, char * argv[]) { + + if(argc != 2) { + std::cerr << "pi " << std::endl; + return 1; + } + + std::atomic successes {0}; + int attempts = atoi(argv[1]); + + std::thread t[num_threads]; + + for (int i = 0; i < num_threads; ++i) { + t[i] = std::thread(slice_of_pi, attempts, i, std::ref(successes)); + } + + + for (int i = 0; i < num_threads; ++i) { + t[i].join(); + } + + float pi = 4 * float(successes) / float(attempts * num_threads); + printf("%0.8f\n", pi); + + return 0; +}