// Copyright (C) 2005-2006 Matthias Troyer // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // An example of a parallel Monte Carlo simulation using some nodes to produce // data and others to aggregate the data #include #include #include #include #include #include #include namespace mpi = boost::mpi; enum {sample_tag, sample_skeleton_tag, sample_broadcast_tag, quit_tag}; void calculate_samples(int sample_length) { int num_samples = 100; std::vector sample(sample_length); // setup communicator by splitting mpi::communicator world; mpi::communicator calculate_communicator = world.split(0); unsigned int num_calculate_ranks = calculate_communicator.size(); // the master of the accumulaion ranks is the first of them, hence // with a rank just one after the last calculation rank int master_accumulate_rank = num_calculate_ranks; // the master of the calculation ranks sends the skeleton of the sample // to the master of the accumulation ranks if (world.rank()==0) world.send(master_accumulate_rank,sample_skeleton_tag,mpi::skeleton(sample)); // next we extract the content of the sample vector, to be used in sending // the content later on mpi::content sample_content = mpi::get_content(sample); // now intialize the parallel random number generator boost::lcg64 engine( boost::random::stream_number = calculate_communicator.rank(), boost::random::total_streams = calculate_communicator.size() ); boost::variate_generator > rng(engine,boost::uniform_real<>()); for (unsigned int i=0; i gathered_results(calculate_communicator.size()); mpi::all_gather(calculate_communicator,local_result,gathered_results); } // we are done: the master tells the accumulation ranks to quit if (world.rank()==0) world.send(master_accumulate_rank,quit_tag); } void accumulate_samples() { std::vector sample; // setup the communicator for all accumulation ranks by splitting mpi::communicator world; mpi::communicator accumulate_communicator = world.split(1); bool is_master_accumulate_rank = accumulate_communicator.rank()==0; // the master receives the sample skeleton if (is_master_accumulate_rank) world.recv(0,sample_skeleton_tag,mpi::skeleton(sample)); // and broadcasts it to all accumulation ranks mpi::broadcast(accumulate_communicator,mpi::skeleton(sample),0); // next we extract the content of the sample vector, to be used in receiving // the content later on mpi::content sample_content = mpi::get_content(sample); // accumulate until quit is called double sum=0.; while (true) { // the accumulation master checks whether we should quit if (world.iprobe(0,quit_tag)) { world.recv(0,quit_tag); for (int i=1; i