VCluster.hpp 22.1 KB
Newer Older
incardon's avatar
incardon committed
1 2 3
#ifndef VCLUSTER
#define VCLUSTER

4
#include "config.h"
incardon's avatar
incardon committed
5
#include <mpi.h>
6
#include "MPI_wrapper/MPI_util.hpp"
incardon's avatar
incardon committed
7 8 9
#include "VCluster_object.hpp"
#include "VCluster_object_array.hpp"
#include "Vector/map_vector.hpp"
10 11 12
#include "MPI_wrapper/MPI_IallreduceW.hpp"
#include "MPI_wrapper/MPI_IrecvW.hpp"
#include "MPI_wrapper/MPI_IsendW.hpp"
incardon's avatar
incardon committed
13
#include <exception>
14
#include "Vector/map_vector.hpp"
15 16 17 18
#ifdef DEBUG
#include "util/check_no_pointers.hpp"
#include "util.hpp"
#endif
incardon's avatar
incardon committed
19 20 21

#define MSG_LENGTH 1024
#define MSG_SEND_RECV 1025
22
#define SEND_SPARSE 4096
incardon's avatar
incardon committed
23 24 25
#define NONE 1
#define NEED_ALL_SIZE 2

26 27
#define SERIVCE_MESSAGE_TAG 16384
#define SEND_RECV_BASE 8192
incardon's avatar
incardon committed
28

incardon's avatar
incardon committed
29 30 31
extern size_t n_vcluster;
extern bool global_mpi_init;

incardon's avatar
incardon committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
///////////////////// Post functions /////////////

template<typename T> void assign(T * ptr1, T * ptr2)
{
	*ptr1 = *ptr2;
};

//////////////////////////////////////////////////

// temporal buffer for reductions
union red
{
	char c;
	unsigned char uc;
	short s;
	unsigned short us;
	int i;
	unsigned int ui;
	float f;
	double d;
};

/*! \brief Virtual Cluster exception
 *
 * This a a class that signal an exception on MPI_WaitAll
 *
 */

class exec_exception: public std::exception
{
  virtual const char* what() const throw()
  {
    return "One or more request has failed or reported an error";
  }
};

/*! \brief This class is virtualize the cluster as a set of processing unit
 *         and communication unit
 *
 * This class virtualize the cluster as a set of processing unit and communication
 * unit. It can execute any vcluster_exe
 *
 */

class Vcluster
{
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	//! NBX has a potential pitfall that must be addressed
	//! NBX Send all the messages and than probe for incoming messages
	//! If there is an incoming message it receive it producing
	//! an acknowledge notification on the sending processor.
	//! when all the sends has been acknowledged the processor call the MPI_Ibarrier
	//! when all the processor call MPI_Ibarrier all send has been received.
	//! While the processors are waiting for the MPI_Ibarrier to complete on all processor
	//! they are still have to probe for incoming message, Unfortunately some processor
	//! can receive acnoledge from the MPI_Ibarrier before others and this mean that some
	//! processor can exit the probing status before others, these processor can in theory
	//! start new communications while the other processor are still in probing status producing
	//! a wrong send/recv association to
	//! resolve this problem an incremental NBX_cnt is used as message TAG to distinguish that the
	//! messages come from other send or subsequent NBX procedures
	size_t NBX_cnt = 0;

incardon's avatar
incardon committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
	// temporal vector used for meta-communication
	// ( or meta-data before the real communication )
	openfpm::vector<size_t> proc_com;

	// vector that contain the scatter map (it is basically an array of one)
	openfpm::vector<int> map_scatter;

	// vector of MPI requests
	openfpm::vector<MPI_Request> req;

	// vector of MPI status
	openfpm::vector<MPI_Status> stat;

	// vector of functions to execute after all the request has been performed
	std::vector<int> post_exe;

	// Object array


	// Single objects

	// number of processes
	int size;
	// actual rank
	int rank;

	// number of processing unit per process
	int numPE = 1;

	/* This buffer is a temporal buffer for reductions
	 *
	 * MPI_Iallreduce does not accept recv and send buffer to be the same
	 * r is used to overcome this problem (is given as second parameter)
	 * after the execution the data is copied back
	 *
	 */
	std::vector<red> r;

public:

	// Finalize the MPI program
	~Vcluster()
	{
incardon's avatar
incardon committed
137 138 139 140 141
		n_vcluster--;

		// if there are no other vcluster instances finalize
		if (n_vcluster == 0)
			MPI_Finalize();
incardon's avatar
incardon committed
142 143 144 145 146
	}

	//! \brief Virtual cluster constructor
	Vcluster(int *argc, char ***argv)
	{
incardon's avatar
incardon committed
147 148 149 150 151 152 153 154
		n_vcluster++;

		// Check if MPI is already initialized
		if (global_mpi_init == false)
		{
			MPI_Init(argc,argv);
			global_mpi_init = true;
		}
incardon's avatar
incardon committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

		//! Get the total number of process
		//! and the rank of this process

		MPI_Comm_size(MPI_COMM_WORLD, &size);
		MPI_Comm_rank(MPI_COMM_WORLD, &rank);

#ifdef MEMLEAK_CHECK
			process_v_cl = rank;
#endif

		//! create and fill map scatter with one
		map_scatter.resize(size);

		for (size_t i = 0 ; i < map_scatter.size() ; i++)
		{
			map_scatter.get(i) = 1;
		}
	}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
#ifdef DEBUG

	/*! \brief Check for wrong types
	 *
	 * In general we do not know if a type T make sense to be sent or not, but if it has pointer
	 * inside it does not. This function check if the basic type T has a method called noPointers,
	 * This function in general notify if T has internally pointers. If T has pointer an error
	 * is printed, is T does not have the method a WARNING is printed
	 *
	 * \tparam T type to check
	 *
	 */
	template<typename T> void checkType()
	{
		// if T is a primitive like int, long int, float, double, ... make sense
		// (pointers, l-references and r-references are not fundamentals)
		if (std::is_fundamental<T>::value == true)
			return;

		// if it is a pointer make no sense
		if (std::is_pointer<T>::value == true)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " is a pointer, sending pointers values has no sense\n";

		// if it is an l-value reference make no send
		if (std::is_lvalue_reference<T>::value == true)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " is a pointer, sending pointers values has no sense\n";

		// if it is an r-value reference make no send
		if (std::is_rvalue_reference<T>::value == true)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " is a pointer, sending pointers values has no sense\n";

		// ... if not, check that T has a method called noPointers
		switch (check_no_pointers<T>::value())
		{
			case PNP::UNKNOWN:
			{
				std::cerr << "Warning: " << __FILE__ << ":" << __LINE__ << " impossible to check the type " << demangle(typeid(T).name()) << " please consider to add a static method \"void noPointers()\" \n" ;
				break;
			}
			case PNP::POINTERS:
			{
				std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " has pointers inside, sending pointers values has no sense\n";
				break;
			}
			default:
			{

			}
		}
	}

#endif

incardon's avatar
incardon committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	//! Get the total number of processing units
	size_t getProcessingUnits()
	{
		return size*numPE;
	}

	//! Get the process unit id
	size_t getProcessUnitID()
	{
		return rank;
	}

	/*! \brief Allocate a set of objects
	 *
	 * \tparam obj
	 * \param n number of object
	 *
	 * \return an object representing an array of objects
	 *
	 */
	template <typename obj> Vcluster_object_array<obj> allocate(size_t n)
	{
		// Vcluster object array
		Vcluster_object_array<obj> vo;

		// resize the array
		vo.resize(n);

		// Create the object on memory and return a Vcluster_object_array
		return vo;
	}

	/*! \brief Sum the number across all processors and get the result
	 *
	 * \param num to reduce, input and output
	 *
	 */

	template<typename T> void reduce(T & num)
	{
268 269 270 271
#ifdef DEBUG
		checkType<T>();
#endif

incardon's avatar
incardon committed
272 273 274 275 276 277 278 279 280
		// reduce over MPI

		// Create one request
		req.add();

		// reduce
		MPI_IallreduceW<T>::reduce(num,MPI_SUM,req.last());
	}

incardon's avatar
incardon committed
281 282 283 284 285 286 287 288
	/*! \brief Get the maximum number across all processors (or reduction with insinity norm)
	 *
	 * \param num to reduce
	 *
	 */

	template<typename T> void max(T & num)
	{
289 290 291
#ifdef DEBUG
		checkType<T>();
#endif
incardon's avatar
incardon committed
292 293 294 295 296 297 298 299 300
		// reduce over MPI

		// Create one request
		req.add();

		// reduce
		MPI_IallreduceW<T>::reduce(num,MPI_MAX,req.last());
	}

incardon's avatar
incardon committed
301 302 303 304 305 306 307 308 309
	// vector of pointers of send buffers
	openfpm::vector<void *> ptr_send;

	// vector of the size of send buffers
	openfpm::vector<size_t> sz_send;

	// sending map
	openfpm::vector<size_t> map;

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	// Distributed processor graph
	MPI_Comm proc_comm_graph;

	/*! \brief
	 *
	 * Set the near processor of this processors
	 *
	 */

	openfpm::vector<size_t> NN_proc;

	void setLocality(openfpm::vector<size_t> NN_proc)
	{
		// Number of sources in the graph, and sources processors
		size_t sources = NN_proc.size();
		openfpm::vector<int> src_proc;

		// number of destination in the graph
		size_t dest = NN_proc.size();
		openfpm::vector<int> dest_proc;

		// insert in sources and out sources
		for (size_t i = 0; i < NN_proc.size() ; i++)
		{
			src_proc.add(NN_proc.get(i));
			dest_proc.add(NN_proc.get(i));
			// Copy the vector
			this->NN_proc.get(i) = NN_proc.get(i);
		}

		MPI_Dist_graph_create_adjacent(MPI_COMM_WORLD,sources,&src_proc.get(0),(const int *)MPI_UNWEIGHTED,dest,&dest_proc.get(0),(const int *)MPI_UNWEIGHTED,MPI_INFO_NULL,true,&proc_comm_graph);
	}

	/*! \brief Send and receive multiple messages within local processors
	 *
	 * It send multiple messages and receive
	 * other multiple messages, all the processor must call this
	 * function
	 *
	 * \param prc list of processors with which it should communicate
	 *
incardon's avatar
incardon committed
351
	 * \param v vector containing the data to send (it is allowed to have 0 size vector)
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
	 *
	 * \param msg_alloc This is a call-back with the purpose of allocate space
	 *        for the incoming message and give back a valid pointer, the 6 parameters
	 *        in the call-back are in order:
	 *        1) message size required to receive from i
	 *        2) total message size to receive from all the processors
	 *        3) the total number of processor want to communicate with you
	 *        4) processor id
	 *        5) ri request id (it is an id that goes from 0 to total_p, and is unique
	 *           every time message_alloc is called)
	 *        6) void pointer parameter for additional data to pass to the call-back
	 *
	 * \param opt options, NONE or NEED_ALL_SIZE, with NEED_ALL_SIZE the allocation
	 *        callback will not be called until all the message size will be
	 *        gathered, [usefull for example with you want to allocate one big buffer
	 *        to gather all the messages]
	 *
	 */

	template<typename T> void sendrecvMultipleMessagesNBX(openfpm::vector< size_t > & prc, openfpm::vector< T > & data, void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt=NONE)
	{
373 374 375
#ifdef DEBUG
		checkType<typename T::value_type>();
#endif
376 377 378 379 380 381 382 383 384 385 386 387 388
		// resize the pointer list
		ptr_send.resize(prc.size());
		sz_send.resize(prc.size());

		for (size_t i = 0 ; i < prc.size() ; i++)
		{
			ptr_send.get(i) = data.get(i).getPointer();
			sz_send.get(i) = data.get(i).size() * sizeof(typename T::value_type);
		}

		sendrecvMultipleMessagesNBX(prc.size(),(size_t *)sz_send.getPointer(),(size_t *)prc.getPointer(),(void **)ptr_send.getPointer(),msg_alloc,ptr_arg,opt);
	}

incardon's avatar
incardon committed
389 390 391

	/*! \brief Send and receive multiple messages
	 *
392
	 * It send multiple messages and receive
incardon's avatar
incardon committed
393 394 395 396 397
	 * other multiple messages, all the processor must call this
	 * function
	 *
	 * \param prc list of processors with which it should communicate
	 *
398 399
	 * \param nn_prc near processors
	 *
incardon's avatar
incardon committed
400 401 402
	 * \param v vector containing the data to send
	 *
	 * \param msg_alloc This is a call-back with the purpose of allocate space
403 404 405 406 407 408 409 410 411
	 *        for the incoming message and give back a valid pointer, the 6 parameters
	 *        in the call-back are in order:
	 *        1) message size required to receive from i
	 *        2) total message size to receive from all the processors
	 *        3) the total number of processor want to communicate with you
	 *        4) processor id
	 *        5) ri request id (it is an id that goes from 0 to total_p, and is unique
	 *           every time message_alloc is called)
	 *        6) void pointer parameter for additional data to pass to the call-back
incardon's avatar
incardon committed
412 413 414 415 416 417 418 419
	 *
	 * \param opt options, NONE or NEED_ALL_SIZE, with NEED_ALL_SIZE the allocation
	 *        callback will not be called until all the message size will be
	 *        gathered, [usefull for example with you want to allocate one big buffer
	 *        to gather all the messages]
	 *
	 */

420
	template<typename T> void sendrecvMultipleMessagesPCX(openfpm::vector< size_t > & prc, openfpm::vector< T > & data, void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt=NONE)
incardon's avatar
incardon committed
421
	{
422 423 424
#ifdef DEBUG
		checkType<typename T::value_type>();
#endif
incardon's avatar
incardon committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
		// resize map with the number of processors
		map.resize(size);

		// reset the sending buffer
		map.fill(0);

		// create sending map
		for (size_t i = 0 ; i < prc.size() ; i++)
		{map.get(prc.get(i)) = 1;}

		// resize the pointer list
		ptr_send.resize(prc.size());
		sz_send.resize(prc.size());

		for (size_t i = 0 ; i < prc.size() ; i++)
		{
			ptr_send.get(i) = data.get(i).getPointer();
			sz_send.get(i) = data.get(i).size() * sizeof(typename T::value_type);
		}

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
		sendrecvMultipleMessagesPCX(prc.size(),(size_t *)map.getPointer(),(size_t *)sz_send.getPointer(),(size_t *)prc.getPointer(),(void **)ptr_send.getPointer(),msg_alloc,ptr_arg,opt);
	}

	/*! \brief Send and receive multiple messages local
	 *
	 * It send multiple messages to the near processor the and receive
	 * other multiple messages from the, all the processor must call this
	 * function
	 *
	 * \param n_send number of send this processor must do
	 *
	 * \param sz the array contain the size of the message for each processor
	 *        (zeros must be omitted)
	 *
	 *        [Example] for the previous patter 5 10 15 4 mean processor 1
	 *        message size 5 byte, processor 6 message size 10 , ......
	 *
	 * \param prc list of processor with which it should communicate
	 *        [Example] for the previous case should be
	 *        1 6 7 8 (prc and mp contain the same information in different
	 *        format, giving both reduce the computation)
	 *
	 * \param ptr array that contain the messages pointers
	 *
	 * \param msg_alloc This is a call-back with the purpose of allocate space
	 *        for the incoming message and give back a valid pointer, the 6 parameters
	 *        in the call-back are in order:
	 *        1) message size required to receive from i
	 *        2) total message size to receive from all the processors
	 *        3) the total number of processor want to communicate with you
	 *        4) processor id
	 *        5) ri request id (it is an id that goes from 0 to total_p, and is unique
	 *           every time message_alloc is called)
	 *        6) void pointer parameter for additional data to pass to the call-back
	 *
	 * \param opt options, NONE (ignored in this moment)
	 *
	 */

	void sendrecvMultipleMessagesNBX(size_t n_send , size_t sz[], size_t prc[] , void * ptr[], void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt)
	{
		req.clear();
		// Do MPI_Issend

		for (size_t i = 0 ; i < n_send ; i++)
		{
incardon's avatar
incardon committed
491 492 493
			if (sz[i] != 0)
			{
				req.add();
494
				MPI_SAFE_CALL(MPI_Issend(ptr[i], sz[i], MPI_BYTE, prc[i], SEND_SPARSE + NBX_cnt, MPI_COMM_WORLD,&req.last()));
incardon's avatar
incardon committed
495
			}
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
		}

		size_t rid = 0;
		int flag = false;

		bool reached_bar_req = false;
		MPI_Request bar_req;

		// Wait that all the send are acknowledge
		do
		{
			// flag that notify that this processor reach the barrier
			// Barrier request

			MPI_Status stat_t;
			int stat = false;
512
			MPI_SAFE_CALL(MPI_Iprobe(MPI_ANY_SOURCE,SEND_SPARSE + NBX_cnt,MPI_COMM_WORLD,&stat,&stat_t));
513

514
			// If I have an incoming message and is related to this NBX communication
515 516 517 518 519 520 521 522 523 524 525
			if (stat == true)
			{
				// Get the message size
				int msize;
				MPI_SAFE_CALL(MPI_Get_count(&stat_t,MPI_BYTE,&msize));

				// Get the pointer to receive the message
				void * ptr = msg_alloc(msize,0,0,stat_t.MPI_SOURCE,rid,ptr_arg);

				rid++;

526
				MPI_SAFE_CALL(MPI_Recv(ptr,msize,MPI_BYTE,stat_t.MPI_SOURCE,SEND_SPARSE+NBX_cnt,MPI_COMM_WORLD,&stat_t));
527 528 529 530 531 532 533
			}

			// Check the status of all the MPI_issend and call the barrier if finished

			if (reached_bar_req == false)
			{
				int flag = false;
incardon's avatar
incardon committed
534 535 536 537
				if (req.size() != 0)
				{MPI_SAFE_CALL(MPI_Testall(req.size(),&req.get(0),&flag,MPI_STATUSES_IGNORE));}
				else
					flag = true;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

				// If all send has been completed
				if (flag == true)
				{MPI_SAFE_CALL(MPI_Ibarrier(MPI_COMM_WORLD,&bar_req));reached_bar_req = true;}
			}

			// Check if all processor reach the async barrier
			if (reached_bar_req)
				MPI_Test(&bar_req,&flag,MPI_STATUSES_IGNORE);
		} while (flag == false);

		// Remove the executed request

		req.clear();
		stat.clear();
553 554 555

		// Circular counter
		NBX_cnt = (NBX_cnt + 1) % 1024;
incardon's avatar
incardon committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
	}

	/*! \brief Send and receive multiple messages
	 *
	 * It send multiple (to more than one) messages and receive
	 * other multiple messages, all the processor must call this
	 * function
	 *
	 * \param n_send number of send this processor must do
	 *
	 * \param map array containing an array of unsigned chars that
	 *        specify the communication pattern of the processor
	 *
	 *        [Example]   0 1 0 0 0 0 1 1 1 mean that the processor
	 *        communicate with the processor 1 6 7 8
	 *
	 * \param sz the array contain the size of the message for each processor
	 *        (zeros must be omitted)
	 *
	 *        [Example] for the previous patter 5 10 15 4 mean processor 1
	 *        message size 5 byte, processor 6 message size 10 , ......
	 *
	 * \param prc list of processor with which it should communicate
	 *        [Example] for the previous case should be
	 *        1 6 7 8 (prc and mp contain the same information in different
	 *        format, giving both reduce the computation)
	 *
	 * \param ptr array that contain the message (zero lengh must be omitted)
	 *
	 * \param msg_alloc This is a call-back with the purpose of allocate space
	 *        for the incoming message and give back a valid pointer, the 3 parameters
	 *        in the call-back are  , total message to receive, i processor id from witch
	 *        to receive
	 *
	 * \param opt options, NONE or NEED_ALL_SIZE, with NEED_ALL_SIZE the allocation
	 *        callback will not be called until all the message size will be
	 *        gathered, [usefull for example with you want to allocate one big buffer
	 *        to gather all the messages]
	 *
	 */

597
	void sendrecvMultipleMessagesPCX(size_t n_send, size_t * map, size_t sz[], size_t prc[] , void * ptr[], void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt)
incardon's avatar
incardon committed
598 599 600
	{
		req.clear();
		req.add();
incardon's avatar
incardon committed
601
		stat.add();
incardon's avatar
incardon committed
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

		proc_com.resize(1);

		MPI_SAFE_CALL(MPI_Ireduce_scatter(map,&proc_com.get(0),&map_scatter.get(0),MPI_UNSIGNED_LONG,MPI_SUM,MPI_COMM_WORLD,&req.last()));
		MPI_SAFE_CALL(MPI_Waitall(req.size(),&req.get(0),&stat.get(0)));

		// Remove the executed request

		req.clear();
		stat.clear();

		// Allocate the temporal buffer to store the message size for each processor

		size_t n_proc_com = proc_com.get(0);
		proc_com.resize(n_proc_com * 2);

		// queue n_proc_com MPI_Irecv with source ANY_SOURCE to get
		// the message length from each processor and
		//  send the message length to each processor

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
			req.add();
			MPI_SAFE_CALL(MPI_Irecv(&proc_com.get(i),1,MPI_UNSIGNED_LONG,MPI_ANY_SOURCE,MSG_LENGTH,MPI_COMM_WORLD,&req.last()));
		}

		for (size_t i = 0 ; i < n_send ; i++)
		{
			req.add();
			MPI_SAFE_CALL(MPI_Isend(&sz[i],1,MPI_UNSIGNED_LONG,prc[i],MSG_LENGTH,MPI_COMM_WORLD,&req.last()));
		}

		stat.resize(req.size());
635
		if (req.size() != 0) {MPI_SAFE_CALL(MPI_Waitall(req.size(),&req.get(0),&stat.get(0)));}
incardon's avatar
incardon committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661

		// Use proc_com to get the processor id that try to communicate

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
			proc_com.get(n_proc_com+i) = stat.get(i).MPI_SOURCE;
		}

		// Remove the executed request

		req.clear();
		stat.clear();

		// Calculate the total size of the message

		size_t total_msg = 0;

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
			total_msg += proc_com.get(i);
		}

		// Receive the message

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
incardon's avatar
incardon committed
662
			void * ptr = msg_alloc(proc_com.get(i),total_msg,n_proc_com,proc_com.get(n_proc_com+i),i,ptr_arg);
incardon's avatar
incardon committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676

			req.add();
			MPI_SAFE_CALL(MPI_Irecv(ptr,proc_com.get(i),MPI_BYTE,proc_com.get(i+n_proc_com),MSG_SEND_RECV,MPI_COMM_WORLD,&req.last()));
		}

		// Send all the messages this processor must send

		for (size_t i = 0 ; i < n_send ; i++)
		{
			req.add();
			MPI_SAFE_CALL(MPI_Isend(ptr[i],sz[i],MPI_BYTE,prc[i],MSG_SEND_RECV,MPI_COMM_WORLD,&req.last()));
		}

		stat.resize(req.size());
677
		if (req.size() != 0) {MPI_SAFE_CALL(MPI_Waitall(req.size(),&req.get(0),&stat.get(0)));}
incardon's avatar
incardon committed
678 679 680 681 682 683 684

		// Remove the executed request

		req.clear();
		stat.clear();
	}

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
	/*! \brief Send data to a processor
	 *
	 * \warning In order to avoid deadlock every send must be coupled with a recv
	 *          in case you want to send data without knowledge from the other side
	 *          consider to use sendRecvMultipleMessages
	 *
	 * \warning operation are async execute must be called to ensure they are executed
	 *
	 * \see sendRecvMultipleMessages
	 *
	 * \param proc processor id
	 * \param tag id
	 * \param v buffer to send
	 *
	 */
	template<typename T> bool send(size_t proc, size_t tag, openfpm::vector<T> & v)
	{
#ifdef DEBUG
		checkType<T>();
#endif

		// send over MPI

		// Create one request
		req.add();

		// reduce
		MPI_IsendW<T>::send(proc,SEND_RECV_BASE + tag,v,req.last());
	}

	/*! \brief Recv data from a processor
	 *
	 * \warning In order to avoid deadlock every recv must be coupled with a send
	 *          in case you want to send data without knowledge from the other side
	 *          consider to use sendRecvMultipleMessages
	 *
	 * \warning operation are async execute must be called to ensure they are executed
	 *
	 * \see sendRecvMultipleMessages
	 *
	 * \param proc processor id
	 * \param tag id
	 * \param v buffer to send
	 *
	 */
	template<typename T> bool recv(size_t proc, size_t tag, openfpm::vector<T> & v)
	{
#ifdef DEBUG
		checkType<T>();
#endif

		// recv over MPI

		// Create one request
		req.add();

		// reduce
		MPI_IrecvW<T>::recv(proc,SEND_RECV_BASE + tag,v,req.last());
	}

	/*! \brief Execute all the requests
incardon's avatar
incardon committed
746 747 748 749 750 751
	 *
	 */
	void execute()
	{
		int err = 0;

752 753 754 755
		// if req == 0 return
		if (req.size() == 0)
			return;

incardon's avatar
incardon committed
756
		// Wait for all the requests
757
		stat.resize(req.size());
incardon's avatar
incardon committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
		err = MPI_Waitall(req.size(),&req.get(0),&stat.get(0));

		// MPI error get the message and abort MPI
		if (err != MPI_SUCCESS)
		{
			char * error_msg = NULL;
			int len;
			MPI_Error_string(err,error_msg,&len);

			std::cerr << "Error MPI rank " << rank << ": " << error_msg << "\n";

			MPI_Abort(MPI_COMM_WORLD,1);
		}

		//! Remove executed request and status
		req.clear();
		stat.clear();
	}
776 777


incardon's avatar
incardon committed
778 779 780 781 782 783 784 785
};

void init_global_v_cluster(int *argc, char ***argv);

extern Vcluster * global_v_cluster;

#endif