int main(int argc, char *argv[]) { int num_procs, my_rank, len; int if_initialized, ierr; int ver, subver; double start, stop; char MPI_Proc_Name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc, &argv); start = MPI_Wtime(); ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs); ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); ierr = MPI_Get_processor_name(MPI_Proc_Name, &len); ierr = MPI_Initialized(&if_initialized); stop = MPI_Wtime(); printf("Hello from rank %d out of %d, I am on processor %s, if_init is %d\n", my_rank, num_procs, MPI_Proc_Name, if_initialized); MPI_Barrier(MPI_COMM_WORLD); printf("on processor %d elapsed time is: %f\n", my_rank, stop - start); MPI_Barrier(MPI_COMM_WORLD); if (my_rank == 0) { printf("-----------------------\n"); ierr = MPI_Get_version(&ver, &subver); printf("MPI Version is %d.%d\n", ver, subver); } MPI_Finalize(); return 0; }
/* * Returns the major and minor version of MPI. * mpi_version(-Major,-Minor). */ static YAP_Bool mpi_version(term_t YAP_ARG1,...){ int major,minor; MPI_CALL(MPI_Get_version(&major,&minor)); return (YAP_Unify(YAP_ARG1,YAP_MkIntTerm(major)) && YAP_Unify(YAP_ARG2,YAP_MkIntTerm(minor))); }
void IOR_SetVersion_MPIIO(IOR_param_t *test) { int version, subversion; MPI_CHECK(MPI_Get_version(&version, &subversion), "cannot get MPI version"); sprintf(test->apiVersion, "%s (version=%d, subversion=%d)", test->api, version, subversion); } /* IOR_SetVersion_MPIIO() */
JNIEXPORT jobject JNICALL Java_mpi_MPI_getVersionJNI(JNIEnv *env, jclass jthis) { int version, subversion; int rc = MPI_Get_version(&version, &subversion); ompi_java_exceptionCheck(env, rc); return (*env)->NewObject(env, ompi_java.VersionClass, ompi_java.VersionInit, version, subversion); }
void mpi_get_version_f(MPI_Fint *version, MPI_Fint *subversion, MPI_Fint *ierr) { OMPI_SINGLE_NAME_DECL(version); OMPI_SINGLE_NAME_DECL(subversion); *ierr = OMPI_INT_2_FINT(MPI_Get_version(OMPI_SINGLE_NAME_CONVERT(version), OMPI_SINGLE_NAME_CONVERT(subversion))); if (MPI_SUCCESS == OMPI_FINT_2_INT(*ierr)) { OMPI_SINGLE_INT_2_FINT(version); OMPI_SINGLE_INT_2_FINT(subversion); } }
int main(int argc, char **argv) { int rank, size, version, subversion, namelen, universe_size; char processor_name[MPI_MAX_PROCESSOR_NAME], worker_program[100]; MPI_Comm esclavos_comm; MPI_Init(&argc, &argv); /* starts MPI */ MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* get current process id */ MPI_Comm_size(MPI_COMM_WORLD, &size); /* get number of processes */ MPI_Get_processor_name(processor_name, &namelen); MPI_Get_version(&version, &subversion); printf("[maestro] Iniciado proceso maestro %d de %d en %s ejecutando MPI %d.%d\n", rank, size, processor_name, version, subversion); strcpy(worker_program, "./Debug/esclavo"); MPI_Comm_spawn(worker_program, MPI_ARGV_NULL,ESCLAVOS, MPI_INFO_NULL, 0, MPI_COMM_SELF, &esclavos_comm, MPI_ERRCODES_IGNORE); /* Cálculo del número de puntos de intervalo por esclavo */ int n_esclavo = (N +1) / ESCLAVOS; printf("PUNTOS POR ESCLAVO: %d\n", n_esclavo); /* Cálculo de vector de valores de la función */ double dx = (double)(B - A) / (double)N ; double h = ((double)B - (double)A) / (2*(double)N); printf("DIFERENCIAL DE X: %f\n", dx); int i = 0; double y[N+1], y_esclavo[n_esclavo]; // número de puntos = número de intervalos + 1 double x = (double) A; for(i=0;i<N+1;i++){ y[i]= x * x; x+=dx; printf("VALOR DE F(X) EN PUNTO i %d: %f\n", i, y[i]); } MPI_Bcast(&n_esclavo, 1, MPI_INT, MPI_ROOT, esclavos_comm); MPI_Scatter(y, n_esclavo, MPI_DOUBLE, y_esclavo, n_esclavo, MPI_DOUBLE, MPI_ROOT, esclavos_comm); double suma; MPI_Reduce(NULL, &suma, 1, MPI_DOUBLE, MPI_SUM, MPI_ROOT, esclavos_comm); printf("SUMA REDUCIDA ES: %f\n", suma); double integral = (double) dx/3 * ((double)A*(double)A + suma + (double) B * (double) B); printf("RESULTADO DE LA INTEGRAL: %f\n", integral); MPI_Comm_disconnect(&esclavos_comm); MPI_Finalize(); return 0; }
/* Obtiene la info del sistema y a imprime en pantalla */ void obtener_info_sist() { int dont_care, mpi_subversion, mpi_version; struct utsname info; uname(&info); dont_care = MPI_Get_version(&mpi_version,&mpi_subversion); printf("## Arquitectura: \t%s\n",info.machine); printf("## Sistema: \t%s\n", info.sysname); printf("## Release : \t%s\n",info.release); printf("## Version : \t%s\n",info.version); printf("## MPI Version : \t%-d.%-d\n",mpi_version,mpi_subversion); printf("\n"); return; }
int main(int argc, char * argv[]) { int myrank; char processor_name[20]; int processor_len; int version_info; int version_len; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); //MPI_Get_processor_name MPI_Get_processor_name(processor_name, &processor_len); MPI_Get_version(&version_info, &version_len); printf("process %d on %s--%d version is %d--%d\n", myrank, processor_name, processor_len, version_info, version_len); fprintf(stderr, "process %d on %s--%d version is %d--%d\n", myrank, processor_name, processor_len, version_info, version_len); MPI_Finalize(); return 0; }
/** * @brief return the MPI version, runtime if possible otherwise that used when * built. * * @result description of the MPI version. */ const char *mpi_version(void) { static char version[80] = {0}; #ifdef WITH_MPI int std_version, std_subversion; /* Check that the library implements the version string routine */ #ifdef MPI_MAX_LIBRARY_VERSION_STRING static char lib_version[MPI_MAX_LIBRARY_VERSION_STRING] = {0}; int len; MPI_Get_library_version(lib_version, &len); /* Find first \n and truncate string to this length, can get many lines from * some MPIs (MPICH). */ char *ptr = strchr(lib_version, '\n'); if (ptr != NULL) *ptr = '\0'; /* Also arbitrarily truncate to keep down to one line, Open MPI, * check for last comma and keep to ~60 chars max. */ strcpy(lib_version+60, "..."); ptr = strrchr(lib_version, ','); if (ptr != NULL) *ptr = '\0'; #else /* Use autoconf guessed value. */ static char lib_version[60] = {0}; snprintf(lib_version, 60, "%s", SWIFT_MPI_LIBRARY); #endif /* Numeric version. */ MPI_Get_version(&std_version, &std_subversion); snprintf(version, 80, "%s (MPI std v%i.%i)", lib_version, std_version, std_subversion); #else sprintf(version, "Code was not compiled with MPI support"); #endif return version; }
int main( int argc, char *argv[] ) { int errs = 0; int majversion, subversion; MTest_Init( &argc, &argv ); MPI_Get_version( &majversion, &subversion ); if (majversion != MPI_VERSION) { errs++; printf( "Major version is %d but is %d in the mpi.h file\n", majversion, MPI_VERSION ); } if (subversion != MPI_SUBVERSION) { errs++; printf( "Minor version is %d but is %d in the mpi.h file\n", subversion, MPI_SUBVERSION ); } MTest_Finalize( errs ); MPI_Finalize(); return 0; }
int main(int argc, char *argv[]) { info = (struct test_info *)malloc(sizeof(struct test_info)); test_info_init(info); info->test_type = 0; info->msg_count=50; struct plat_opts_config_mpilogme config; SDF_boolean_t success = SDF_TRUE; uint32_t numprocs; int tmp, namelen, mpiv = 0, mpisubv = 0, i; char processor_name[MPI_MAX_PROCESSOR_NAME]; int msg_init_flags = SDF_MSG_MPI_INIT; config.inputarg = 0; config.msgtstnum = 500; /* We may not need to gather anything from here but what the heck */ loadProperties("/opt/schooner/config/schooner-med.properties"); // TODO get filename from command line /* make sure this is first in order to get the the mpi init args */ success = plat_opts_parse_mpilogme(&config, argc, argv) ? SDF_FALSE : SDF_TRUE; printf("input arg %d msgnum %d success %d\n", config.inputarg, config.msgtstnum, success); fflush(stdout); myid = sdf_msg_init_mpi(argc, argv, &numprocs, &success, msg_init_flags); info->myid = myid; if ((!success) || (myid < 0)) { printf("Node %d: MPI Init failure... exiting - errornum %d\n", myid, success); fflush(stdout); MPI_Finalize(); return (EXIT_FAILURE); } int debug = 0; while(debug); tmp = init_msgtest_sm((uint32_t)myid); /* Enable this process to run threads across 2 cpus, MPI will default to running all threads * on only one core which is not what we really want as it forces the msg thread to time slice * with the fth threads that send and receive messsages * first arg is the number of the processor you want to start off on and arg #2 is the sequential * number of processors from there */ //lock_processor(0, 7); lock_processor(myid * 4, 4); info->lock_cpu = 4; sleep(1); msg_init_flags = msg_init_flags | SDF_MSG_RTF_DISABLE_MNGMT; /* Startup SDF Messaging Engine FIXME - dual node mode still - pnodeid is passed and determined * from the number of processes mpirun sees. */ sdf_msg_init(myid, &pnodeid, msg_init_flags); MPI_Get_version(&mpiv, &mpisubv); MPI_Get_processor_name(processor_name, &namelen); printf("Node %d: MPI Version: %d.%d Name %s \n", myid, mpiv, mpisubv, processor_name); fflush(stdout); plat_log_msg( PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: Completed Msg Init.. numprocs %d pnodeid %d Starting Test\n", myid, numprocs, pnodeid); info->pnodeid = pnodeid; for (i = 0; i < 2; i++) { sleep(2); plat_log_msg(PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: Number of sleeps %d\n", myid, i); } fthInit(); /* SAVE THIS may need to play with the priority later */ #if 0 struct sched_param param; int newprio = 60; pthread_attr_t hi_prior_attr; pthread_attr_init(&hi_prior_attr); pthread_attr_setschedpolicy(&hi_prior_attr, SCHED_FIFO); pthread_attr_getschedparam(&hi_prior_attr, ¶m); param.sched_priority = newprio; pthread_attr_setschedparam(&hi_prior_attr, ¶m); pthread_create(&fthPthread, &hi_prior_attr, &fthPthreadRoutine, NULL); #endif pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&fthPthread, &attr, &SinglePtlSequentialPressPthreadRoutine, NULL); plat_log_msg(PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: Created pthread for FTH %d\n", myid, i); info->pthread_info = 1; info->fth_info = 2; pthread_join(fthPthread, NULL); plat_log_msg(PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: SDF Messaging Test Complete - i %d\n", myid, i); /* Lets stop the messaging engine this will block until they complete */ /* FIXME arg is the threadlvl */ sdf_msg_stopmsg(myid, SYS_SHUTDOWN_SELF); if (numprocs > 1) { sdf_msg_nsync(myid, (myid == 0 ? 1 : 0)); } plat_shmem_detach(); info->success++; if (myid == 0) { sched_yield(); printf("Node %d: Exiting message test after yielding... Calling MPI_Finalize\n", myid); fflush(stdout); sched_yield(); MPI_Finalize(); print_test_info(info); test_info_final(info); } else { printf("Node %d: Exiting message test... Calling MPI_Finalize\n", myid); fflush(stdout); sched_yield(); MPI_Finalize(); } printf("Successfully ends\n"); return (EXIT_SUCCESS); }
FORT_DLL_SPEC void FORT_CALL mpi_get_version_ ( MPI_Fint *v1, MPI_Fint *v2, MPI_Fint *ierr ){ *ierr = MPI_Get_version( v1, v2 ); }
int main(int argc, char *argv[]){ MothurOut* m = MothurOut::getInstance(); try { signal(SIGINT, ctrlc_handler ); time_t ltime = time(NULL); /* calendar time */ string logFileName = "mothur." + toString(ltime) + ".logfile"; #ifdef USE_MPI MPI_Init(&argc, &argv); #endif m->setFileName(logFileName); #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) system("clear"); #else system("CLS"); #endif #ifdef MOTHUR_FILES string temp = MOTHUR_FILES; //add / to name if needed string lastChar = temp.substr(temp.length()-1); #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) if (lastChar != "/") { temp += "/"; } #else if (lastChar != "\\") { temp += "\\"; } #endif temp = m->getFullPathName(temp); m->setDefaultPath(temp); #endif #ifdef USE_MPI int version, subversion; MPI_Get_version(&version, &subversion); #endif //get releaseDate from Make string releaseDate = RELEASE_DATE; string mothurVersion = VERSION; m->setReleaseDate(releaseDate); m->setVersion(mothurVersion); //will make the gui output "pretty" bool outputHeader = true; if (argc>1) { string guiInput = argv[1]; if (guiInput[0] == '+') { outputHeader = false; } if (guiInput[0] == '-') { outputHeader = false; } } if (outputHeader) { //version #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) #if defined (__APPLE__) || (__MACH__) m->mothurOutJustToLog("Mac version"); m->mothurOutEndLine(); m->mothurOutEndLine(); #else m->mothurOutJustToLog("Linux version"); m->mothurOutEndLine(); m->mothurOutEndLine(); #endif #else m->mothurOutJustToLog("Windows version"); m->mothurOutEndLine(); m->mothurOutEndLine(); #endif #ifdef USE_READLINE m->mothurOutJustToLog("Using ReadLine"); m->mothurOutEndLine(); m->mothurOutEndLine(); #endif #ifdef MOTHUR_FILES m->mothurOutJustToLog("Using default file location " + temp); m->mothurOutEndLine(); m->mothurOutEndLine(); #endif #ifdef BIT_VERSION m->mothurOutJustToLog("Running 64Bit Version"); m->mothurOutEndLine(); m->mothurOutEndLine(); #else m->mothurOutJustToLog("Running 32Bit Version"); m->mothurOutEndLine(); m->mothurOutEndLine(); #endif //header m->mothurOut("mothur v." + mothurVersion); m->mothurOutEndLine(); m->mothurOut("Last updated: " + releaseDate); m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("by"); m->mothurOutEndLine(); m->mothurOut("Patrick D. Schloss"); m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("Department of Microbiology & Immunology"); m->mothurOutEndLine(); m->mothurOut("University of Michigan"); m->mothurOutEndLine(); m->mothurOut("*****@*****.**"); m->mothurOutEndLine(); m->mothurOut("http://www.mothur.org"); m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("When using, please cite:"); m->mothurOutEndLine(); m->mothurOut("Schloss, P.D., et al., Introducing mothur: Open-source, platform-independent, community-supported software for describing and comparing microbial communities. Appl Environ Microbiol, 2009. 75(23):7537-41."); m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("Distributed under the GNU General Public License"); m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("Type 'help()' for information on the commands that are available"); m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("Type 'quit()' to exit program"); m->mothurOutEndLine(); #ifdef USE_MPI m->mothurOutJustToLog("Using MPI\tversion "); m->mothurOutJustToLog(toString(version) + "." + toString(subversion) + "\n"); #endif } //srand(54321); srand( (unsigned)time( NULL ) ); Engine* mothur = NULL; bool bail = 0; string input; if(argc>1){ input = argv[1]; //m->mothurOut("input = " + input); m->mothurOutEndLine(); if (input[0] == '#') { m->mothurOutJustToLog("Script Mode"); m->mothurOutEndLine(); m->mothurOutEndLine(); mothur = new ScriptEngine(argv[0], argv[1]); }else if (input[0] == '+') { mothur = new ScriptEngine(argv[0], argv[1]); m->gui = true; }else if (input == "-version") { m->mothurOut("Mothur version=" + mothurVersion + "\nRelease Date=" + releaseDate); m->mothurOutEndLine(); m->mothurOutEndLine(); m->closeLog(); #ifdef USE_MPI MPI_Finalize(); #endif return 0; }else{ m->mothurOutJustToLog("Batch Mode"); m->mothurOutEndLine(); m->mothurOutEndLine(); mothur = new BatchEngine(argv[0], argv[1]); } } else{ m->mothurOutJustToLog("Interactive Mode"); m->mothurOutEndLine(); m->mothurOutEndLine(); mothur = new InteractEngine(argv[0]); } while(bail == 0) { bail = mothur->getInput(); } //closes logfile so we can rename m->closeLog(); string outputDir = mothur->getOutputDir(); string tempLog = mothur->getLogFileName(); bool append = mothur->getAppend(); string newlogFileName; if (tempLog != "") { newlogFileName = outputDir + tempLog; if (!append) { //need this because m->mothurOut makes the logfile, but doesn't know where to put it rename(logFileName.c_str(), newlogFileName.c_str()); //logfile with timestamp }else { ofstream outNewLog; m->openOutputFileAppend(newlogFileName, outNewLog); if (!m->gui) { outNewLog << endl << endl << "*********************************************************************************" << endl << endl; }else { outNewLog << endl; } outNewLog.close(); m->appendFiles(logFileName, newlogFileName); m->mothurRemove(logFileName); } }else{ newlogFileName = outputDir + logFileName; //need this because m->mothurOut makes the logfile, but doesn't know where to put it rename(logFileName.c_str(), newlogFileName.c_str()); //logfile with timestamp } if (mothur != NULL) { delete mothur; } #ifdef USE_MPI MPI_Finalize(); #endif return 0; } catch(exception& e) { m->errorOut(e, "mothur", "main"); exit(1); } }
/************************************************************************* * method: initpympi * This is called right after python has been initialized. MPI has already * been initialized here * ************************************************************************/ void initpympi() { PyObject* mpiName = 0; char versionString[32]; PyObject* lastWish = 0; int version; int subversion; PyObject* pickleModule = 0; PyObject* pickleDict = 0; PyObject* docString = 0; PyObject* pyWorld = 0; PyObject* member = 0; PyMethodDef* methodPtr = 0; char* docExtra = 0; int myRank = 0; int result = MPI_Comm_rank(MPI_COMM_WORLD, &myRank ); /* ----------------------------------------------- */ /* The IBM poe environment is brain dead */ /* ----------------------------------------------- */ #ifdef _AIX Py_InteractiveFlag++; #endif /* ----------------------------------------------- */ /* Cover our butts on assumptions */ /* ----------------------------------------------- */ Assert( sizeof(MPI_Comm) <= sizeof(long) ); /* ----------------------------------------------- */ /* We subvert the input stream to handle broadcast */ /* ----------------------------------------------- */ Original_ReadlineFunctionPointer = PyOS_ReadlineFunctionPointer; if ( !Original_ReadlineFunctionPointer ) { Original_ReadlineFunctionPointer = PyOS_StdioReadline; } PyOS_ReadlineFunctionPointer = MPI_ReadlineFunctionPointer; /* ----------------------------------------------- */ /* Setup the initial mpi module */ /* ----------------------------------------------- */ module = Py_InitModule("mpi",MPI_methods); Assert(module); PyMPI_dictionary = PyModule_GetDict(module); Assert(PyMPI_dictionary); /* ----------------------------------------------- */ /* Set up a docstring for the mpi module itself */ /* ----------------------------------------------- */ docExtra = DocStringFromMethods(MPI_methods,"mpi\n\nBasic mpi calls\n\n"); Assert(docExtra); docString = PyString_FromString(docExtra); free(docExtra); /* ----------------------------------------------- */ /* We start off with errors handled with flag */ /* ----------------------------------------------- */ if ( MPI_Errhandler_set(MPI_COMM_WORLD,MPI_ERRORS_RETURN) != MPI_SUCCESS ) { PYCHECK( PyErr_SetString(PyExc_SystemError,"MPI Failure -- MPI_Errhandler_set()") ); } /* ----------------------------------------------- */ /* See if we conform! */ /* ----------------------------------------------- */ MPICHECKCOMMLESS( MPI_Get_version(&version,&subversion) ); Assert(version == MPI_VERSION && subversion == MPI_SUBVERSION); /* ----------------------------------------------- */ /* We have some cleanup work to do on exit */ /* ----------------------------------------------- */ PYCHECK( lastWish = PyCFunction_New(&lastwishMethods,module) ); Assert(lastWish); sysExitfunc = PySys_GetObject("exitfunc"); PyErr_Clear(); PYCHECK( PySys_SetObject("exitfunc",lastWish) ); /* ----------------------------------------------- */ /* Set common attributes */ /* ----------------------------------------------- */ PYCHECK( PyDict_SetItemString(PyMPI_dictionary,"stdout",Py_None) ); Py_INCREF(Py_None); PYCHECK( PyString_ConcatFromString(&docString,"name: Name of MPI model (MPICH, LAM, mpi)") ); #ifdef MPICH_NAME PYCHECK( mpiName = PyString_FromString("MPICH") ); #else # ifdef LAM_MPI PYCHECK( mpiName = PyString_FromString("LAM") ); # else PYCHECK( mpiName = PyString_FromString("mpi") ); # endif #endif PYCHECK( PyDict_SetItemString(PyMPI_dictionary,"name",mpiName) ); PYCHECK( PyString_ConcatFromString(&docString,"rank: Rank of MPI_COMM_WORLD communicator\n") ); MPICHECK( MPI_COMM_WORLD, MPI_Comm_rank(MPI_COMM_WORLD,&worldRank)); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"rank", PyInt_FromLong((long)worldRank))); PYCHECK(PyString_ConcatFromString(&docString,"procs: Size of MPI_COMM_WORLD communicator\n")); MPICHECK( MPI_COMM_WORLD, MPI_Comm_size(MPI_COMM_WORLD,&worldProcs)); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"procs", PyInt_FromLong((long)worldProcs))); PYCHECK(PyString_ConcatFromString(&docString,"tick: Tick size of high-resolution timer\n")); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"tick", PyFloat_FromDouble(MPI_Wtick()))); PYCHECK(PyString_ConcatFromString(&docString,"version: String showing mpi version\n")); sprintf(versionString,"%d.%d",MPI_VERSION,MPI_SUBVERSION); #if defined(MPICH_NAME) && MPI_VERSION == 1 && MPI_SUBVERSION == 1 && MPI_STATUS_SIZE == 5 strcat(versionString,".2"); /* MPICH 1.1.2 is evil */ #endif PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"version", PyString_FromString(versionString))); PYCHECK(PyString_ConcatFromString(&docString,"COMM_WORLD: MPI_COMM_WORLD communicator\n")); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"COMM_WORLD", PyMPI_Comm(MPI_COMM_WORLD))); PYCHECK(PyString_ConcatFromString(&docString,"COMM_NULL: MPI_COMM_NULL communicator (non-functional)\n")); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"COMM_NULL", PyMPI_Comm(MPI_COMM_NULL))); PYCHECK(PyString_ConcatFromString(&docString,"MAX: MPI_MAX\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MAX", PyInt_FromLong((long)MPI_MAX)));*/ reduceOpLookup[eMaxOp] = MPI_MAX; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MAX", PyInt_FromLong((long)eMaxOp))); PYCHECK(PyString_ConcatFromString(&docString,"MIN: MPI_MIN\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MIN", PyInt_FromLong((long)MPI_MIN)));*/ reduceOpLookup[eMinOp] = MPI_MIN; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MIN", PyInt_FromLong((long)eMinOp))); PYCHECK( PyString_ConcatFromString(&docString,"SUM: MPI_SUM\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"SUM", PyInt_FromLong((long)MPI_SUM)));*/ reduceOpLookup[eSumOp] = MPI_SUM; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"SUM", PyInt_FromLong((long)eSumOp))); PYCHECK( PyString_ConcatFromString(&docString,"PROD: MPI_PROD\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"PROD", PyInt_FromLong((long)MPI_PROD)));*/ reduceOpLookup[eProdOp] = MPI_PROD; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"PROD", PyInt_FromLong((long)eProdOp))); PYCHECK( PyString_ConcatFromString(&docString,"LAND: MPI_LAND\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"LAND", PyInt_FromLong((long)MPI_LAND)));*/ reduceOpLookup[eLandOp] = MPI_LAND; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"LAND", PyInt_FromLong((long)eLandOp))); PYCHECK( PyString_ConcatFromString(&docString,"BAND: MPI_BAND\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"BAND", PyInt_FromLong((long)MPI_BAND)));*/ reduceOpLookup[eBandOp] = MPI_BAND; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"BAND", PyInt_FromLong((long)eBandOp))); PYCHECK( PyString_ConcatFromString(&docString,"LOR: MPI_LOR\n")); /*PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"LOR", PyInt_FromLong((long)MPI_LOR)));*/ reduceOpLookup[eLorOp] = MPI_LOR; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"LOR", PyInt_FromLong((long)eLorOp))); PYCHECK( PyString_ConcatFromString(&docString,"BOR: MPI_BOR\n")); /* PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"BOR", PyInt_FromLong((long)MPI_BOR)));*/ reduceOpLookup[eBorOp] = MPI_BOR; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"BOR", PyInt_FromLong((long)eBorOp))); PYCHECK( PyString_ConcatFromString(&docString,"LXOR: MPI_LXOR\n")); /* PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"LXOR", PyInt_FromLong((long)MPI_LXOR)));*/ reduceOpLookup[eLxorOp] = MPI_LXOR; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"LXOR", PyInt_FromLong((long)eLxorOp))); PYCHECK( PyString_ConcatFromString(&docString,"BXOR: MPI_BXOR\n")); /* PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"BXOR", PyInt_FromLong((long)MPI_BXOR)));*/ reduceOpLookup[eBxorOp] = MPI_BXOR; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"BXOR", PyInt_FromLong((long)eBxorOp))); PYCHECK( PyString_ConcatFromString(&docString,"MINLOC: MPI_MINLOC\n")); /* PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MINLOC", PyInt_FromLong((long)MPI_MINLOC)));*/ reduceOpLookup[eMinlocOp] = MPI_MINLOC; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MINLOC", PyInt_FromLong((long)eMinlocOp))); PYCHECK( PyString_ConcatFromString(&docString,"MAXLOC: MPI_MAXLOC\n")); /* PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MAXLOC", PyInt_FromLong((long)MPI_MAXLOC)));*/ reduceOpLookup[eMaxlocOp] = MPI_MAXLOC; PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MAXLOC", PyInt_FromLong((long)eMaxlocOp))); PYCHECK( PyString_ConcatFromString(&docString,"ANY_SOURCE: MPI_ANY_SOURCE (used for untargeted recv)\n")); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"ANY_SOURCE", PyInt_FromLong((long)MPI_ANY_SOURCE))); PYCHECK( PyString_ConcatFromString(&docString,"ANY_TAG: MPI_ANY_TAG (used for untargeted recv)\n")); PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"ANY_TAG", PyInt_FromLong((long)MPI_ANY_TAG))); /* ----------------------------------------------- */ /* We set up an internal communicator for PYTHON */ /* messaging and another for Python I/O */ /* ----------------------------------------------- */ MPICHECK( MPI_COMM_WORLD, MPI_Comm_dup(MPI_COMM_WORLD,&PyMPI_COMM_WORLD)); MPICHECK( MPI_COMM_WORLD, MPI_Comm_dup(MPI_COMM_WORLD,&PyMPI_COMM_INPUT)); PYCHECK( PyString_ConcatFromString(&docString,"WORLD: Internal Python communicator\n") ); PYCHECK( pyWorld = PyMPI_Comm(PyMPI_COMM_WORLD) ); PYCHECK( PyDict_SetItemString(PyMPI_dictionary,"WORLD",pyWorld) ); /* ----------------------------------------------- */ /* Fetch member functions to appear as mpi.xxxx */ /* Make pyWorld immortal to avoid dealloc issues */ /* Magic Rating: 10/10 */ /* ----------------------------------------------- */ Py_INCREF(pyWorld); for(methodPtr = PyMPIMethods_Comm; methodPtr->ml_name; ++methodPtr) { PYCHECK( member = PyObject_GetAttrString(pyWorld,methodPtr->ml_name) ); Py_INCREF(member); PYCHECK( PyDict_SetItemString(PyMPI_dictionary,methodPtr->ml_name,member) ); } /* ----------------------------------------------- */ /* Set up the overloaded input */ /* ----------------------------------------------- */ PYCHECK( overloadedInput = PyMPI_File(worldRank != 0,PySys_GetObject("stdin"),PyMPI_COMM_INPUT) ); Py_INCREF(overloadedInput); PyDict_SetItemString(PyMPI_dictionary,"stdin",overloadedInput); PySys_SetObject("stdin",overloadedInput); /* ----------------------------------------------- */ /* Initial model is no output throttle */ /* ----------------------------------------------- */ PYCHECK( PyMPI_UnrestrictedOutput(3) ); /* ----------------------------------------------- */ /* Have to set up some stuff for communicating */ /* arbitrary python objects */ /* ----------------------------------------------- */ /* -- set up PyMPI_pythonPickleType -- */ MPICHECKCOMMLESS( MPI_Type_contiguous(1,MPI_CHAR,&PyMPI_pythonPickleType) ); MPICHECKCOMMLESS( MPI_Type_commit(&PyMPI_pythonPickleType) ); Assert( PyMPI_pythonPickleType != MPI_CHAR ); /* -- set up PyMPI_pythonFuncPickleType -- */ MPICHECKCOMMLESS( MPI_Type_contiguous(1,MPI_CHAR,&PyMPI_pythonFuncPickleType) ); MPICHECKCOMMLESS( MPI_Type_commit(&PyMPI_pythonFuncPickleType) ); Assert( PyMPI_pythonFuncPickleType != MPI_CHAR ); /* -- set up PyMPI_pythonFuncPickleType -- */ pickleModule = PyImport_ImportModule("cPickle"); if ( !pickleModule || PyErr_Occurred() ) { PyErr_Clear(); } else { PYCHECK( pickleDict = PyModule_GetDict(pickleModule) ); PYCHECK( PyMPI_pickleDumperFunction = PyDict_GetItemString(pickleDict,"dumps") ); PYCHECK( PyMPI_pickleLoaderFunction = PyDict_GetItemString(pickleDict,"loads") ); } /* ----------------------------------------------- */ /* Set up the __doc__ string of the communicator */ /* type with more info (based on list) */ /* ----------------------------------------------- */ PyMPIObject_Communicator_Type.tp_doc = DocStringFromMethods(PyMPIMethods_Comm, PyMPIObject_Communicator_Type.tp_doc); /* ----------------------------------------------- */ /* Set up same info in module doc */ /* ----------------------------------------------- */ docExtra = DocStringFromMethods(PyMPIMethods_Comm, "\nAnd these communicator methods map to the Python world communicator (not MPI_COMM_WORLD)\n\n"); Assert(docExtra); PYCHECK( PyString_ConcatFromString(&docString,docExtra) ); free(docExtra); /* ----------------------------------------------- */ /* Stick in the doc string and we're ready to go */ /* ----------------------------------------------- */ PYCHECK( PyDict_SetItemString(PyMPI_dictionary, "__doc__", docString) ); return; pythonError: Assert( PyErr_Occurred() ); return; /* We have set a Python exception, let Python handle it */ }
int main(int argc, char **argv) { int rank, size, version, subversion, namelen, universe_size, jugadorMano, repartidor, sizeMazo, sizeDescartadas; char processor_name[MPI_MAX_PROCESSOR_NAME], worker_program[100]; MPI_Comm juego_comm; Carta mazo[N_CARTAS_MAZO]; Carta mano0[N_CARTAS_MANO]; Carta mano1[N_CARTAS_MANO]; Carta mano2[N_CARTAS_MANO]; Carta mano3[N_CARTAS_MANO]; Carta manoJugadorHumano[N_CARTAS_MANO]; char *caras[] = {"As", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Sota", "Caballo", "Rey"}; char *palos[] = {"Oros", "Copas", "Espadas", "Bastos"}; char *lancesEtiquetas[] = {"Grande", "Chica", "Pares", "Juego", "Al punto"}; int valores[] = {1, 1, 10, 4, 5, 6, 7, 10, 10, 10}; int equivalencias[] = {1, 1, 10, 4, 5, 6, 7, 8, 9, 10}; int piedras[N_PAREJAS] = {0, 0}; int apuestas[N_LANCES + 1] = {0, 0, 0, 0, 0}; int jugadorHumano = 99; int pareja1[6]; // miembro 1 de pareja - miembro 2 de pareja - piedras - rondas - juegos - vacas int pareja2[6]; int ronda = 0; // inicialización de contadores pareja1[0] = 0; pareja1[1] = 2; pareja2[0] = 1; pareja2[1] = 3; int l = 0; for (l = 2; l < 6; l++) { pareja1[l] = 0; pareja2[l] = 0; } int N_PUNTOS_JUEGO = 40; int N_JUEGOS_VACA = 3; int N_VACAS_PARTIDA = 3; int N_PARTIDAS = 1; srand(time(NULL)); /* randomize */ sizeMazo = crearMazo(mazo, caras, palos, valores, equivalencias); /* llena el mazo de cartas */ sizeDescartadas = 0; int ordago = 0; char modo = 'Z'; //1 automático, 0 manual printf("Introduzca el número de partidas (1): \n"); fflush(stdout); scanf(" %d", &N_PARTIDAS); getchar(); fflush(stdout); fflush(stdin); printf("Introduzca el número de vacas (3): \n"); fflush(stdout); scanf(" %d", &N_VACAS_PARTIDA); getchar(); fflush(stdout); fflush(stdin); printf("Introduzca el número de juegos (3): \n"); fflush(stdout); scanf(" %d", &N_VACAS_PARTIDA); getchar(); fflush(stdout); fflush(stdin); printf("Introduzca el número de puntos por juego (40): \n"); fflush(stdout); scanf(" %d", &N_PUNTOS_JUEGO); getchar(); fflush(stdout); fflush(stdin); printf("Introduzca el modo de juego (A:automático, I:interactivo): \n"); while (modo != 'A' || modo != 'I' || modo != 'a' || modo != 'i') { modo = getchar(); if (modo == 'A' || modo == 'I' || modo == 'a' || modo == 'i') { break; } else { getchar(); printf("Introduzca una A o una I\n"); } } printf("Comenzando partida en modo %c\n", modo); if (modo == 'I' || modo == 'i') { jugadorHumano = rand() % (N_JUGADORES + 1 - 0) + 0; //jugadorHumano = 3; printf("El identificador para el jugador humano es: %d\n", jugadorHumano); } printf("[maestro] Tamaño del mazo" " %d\n", sizeMazo); //printMazo(mazo); /*Imprime el mazo*/ printf("\n"); barajarMazo(mazo); /*Baraja el mazo*/ printf("\n"); MPI_Init(&argc, &argv); /* starts MPI */ MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* get current process id */ MPI_Comm_size(MPI_COMM_WORLD, &size); /* get number of processes */ MPI_Get_processor_name(processor_name, &namelen); MPI_Get_version(&version, &subversion); printf("[maestro] Iniciado proceso maestro %d de %d en %s ejecutando MPI %d.%d\n", rank, size, processor_name, version, subversion); if (size != 1) printf("[maestro] Error: sólo debería estar ejecutándose el proceso maestro, pero hay %d procesos ejecutándose\n", size); /* Fijar el total de procesos a ejecutar incluyendo el maestro */ universe_size = 5; strcpy(worker_program, "./jugador"); printf("[maestro] Generando %d procesos ejecutando %s\n", universe_size - 1, worker_program); MPI_Comm_spawn(worker_program, MPI_ARGV_NULL, universe_size - 1, MPI_INFO_NULL, 0, MPI_COMM_SELF, &juego_comm, MPI_ERRCODES_IGNORE); printf("[maestro] Ejecutado proceso maestro con identificador %d de un total de %d\n", rank, size); /* PRIMER INTERCAMBIO DE INFORMACIÓN: maestro a jugadores */ MPI_Bcast(&sizeMazo, 1, MPI_INT, MPI_ROOT, juego_comm);/*Envío del tamaño del mazo */ MPI_Bcast(&sizeDescartadas, 1, MPI_INT, MPI_ROOT, juego_comm);/*Envío del tamaño del mazo de descartadas*/ int corte; /* jugador que realizará el corte */ int N = 0, M = N_JUGADORES - 1; /* valores del intervalo */ corte = M + rand() / (RAND_MAX / (N - M + 1) + 1); /* proceso aleatorio de entre los existentes */ MPI_Bcast(&corte, 1, MPI_INT, MPI_ROOT, juego_comm); /* envío del id de proceso que realizará el corte a todos*/ MPI_Bcast(&modo, 1, MPI_CHAR, MPI_ROOT, juego_comm); MPI_Bcast(&jugadorHumano, 1, MPI_INT, MPI_ROOT, juego_comm); /* envío del id de jugador humano en caso de modo manual*/ enviarMazo(mazo, corte, juego_comm, N_CARTAS_MAZO); /* envío del mazo al jugador que va a cortar la baraja*/ MPI_Recv(&repartidor, 1, MPI_INT, corte, 0, juego_comm, MPI_STATUS_IGNORE); /**************************************************************/ /* Comienzan rondas /**************************************************************/ while ((pareja1[5] != 1 && pareja2[5] != 1)) { //mientras no haya una partida ganada... printf("INICIANDO RONDA %d\n", ronda); if (ronda != 0) { Carta mazo[N_CARTAS_MAZO]; sizeMazo = crearMazo(mazo, caras, palos, valores, equivalencias); /* llena el mazo de cartas */ printf("ATENCION Tamaño mazo: %d\n", sizeMazo); sizeDescartadas = 0; int ordago = 0; barajarMazo(mazo); /*Baraja el mazo*/ } printf("[maestro] El jugador repartidor es: %d\n", repartidor); //int mano = add_mod(postre, 1, 4); //printf("[maestro] El jugador mano es: %d\n", mano); MPI_Bcast(&repartidor, 1, MPI_INT, MPI_ROOT, juego_comm); //envío del repartidor a todos los procesos MPI_Bcast(&sizeMazo, 1, MPI_INT, MPI_ROOT, juego_comm); /* envío del mazo al jugador que va a repartir */ enviarMazo(mazo, repartidor, juego_comm, N_CARTAS_MAZO); /* e/s auxiliar reparto de cartas */ int i = 0; for (i = 0; i <= (N_CARTAS_MANO * N_JUGADORES - 1); i++) { int buffer[3]; MPI_Recv(&buffer, 3, MPI_INT, repartidor, 0, juego_comm, MPI_STATUS_IGNORE); printf("[repartidor %d] Repartida carta %d al jugador %d\n", repartidor, buffer[0], buffer[1]); int siguiente = buffer[1]; MPI_Recv(&buffer, 3, MPI_INT, siguiente, 0, juego_comm, MPI_STATUS_IGNORE); printf("[jugador %d] Jugador %d recibe carta %d \n", buffer[0], buffer[0], buffer[1]); } MPI_Recv(&sizeMazo, 1, MPI_INT, repartidor, 0, juego_comm, MPI_STATUS_IGNORE); recibirMazo(mazo, repartidor, juego_comm, N_CARTAS_MAZO, MPI_STATUS_IGNORE); printf("[maestro] tamaño del mazo: %d\n", sizeMazo); MPI_Bcast(&sizeMazo, 1, MPI_INT, MPI_ROOT, juego_comm); //envío del tamaño del mazo a resto de procesos int siguienteJugador = add_mod(repartidor, 1, 4); jugadorMano = 99; int turno = 0; int turnoDescartes = 1; int bufferSnd[3] = {99, siguienteJugador, turno}; int bufferRcv[3] = {99, siguienteJugador, turno}; int descarte = 99; int contador = 0; // si jugamos con humano, hay que recibir su mano while (jugadorMano == 99) { if ((turno % 4) == 0 && (turno != 0) && (turnoDescartes == 1)) { //turno de descartes // recibe identificador de carta a descartar int descarteHumano = 99; for (i = 0; i < N_CARTAS_MANO; i++) { if ((modo == 'I' || modo == 'i') && (siguienteJugador == jugadorHumano)) { printf("¿Desea descartar %s de %s? (S/N)\n", manoJugadorHumano[i].cara, manoJugadorHumano[i].palo); char c; scanf(" %c", &c); if (c == 'S' || c == 's') { descarteHumano = 1; } else { descarteHumano = 0; } MPI_Send(&descarteHumano, 1, MPI_INT, jugadorHumano, 0, juego_comm); } MPI_Recv(&descarte, 1, MPI_INT, siguienteJugador, 0, juego_comm, MPI_STATUS_IGNORE); if (descarte != 99 && descarte != 98) { marcarDescarte(mazo, N_CARTAS_MAZO, descarte); repartirCarta(mazo[N_CARTAS_MAZO - sizeMazo], siguienteJugador, juego_comm); mazo[N_CARTAS_MAZO - sizeMazo].estado = 1; sizeMazo--; } } MPI_Recv(&bufferRcv[1], 1, MPI_INT, siguienteJugador, 0, juego_comm, MPI_STATUS_IGNORE); siguienteJugador = bufferRcv[1]; contador++; if (contador == N_JUGADORES) { turnoDescartes = 0; contador = 0; } MPI_Bcast(&turnoDescartes, 1, MPI_INT, MPI_ROOT, juego_comm); } else { // mus corrido turnoDescartes = 1; MPI_Bcast(&turnoDescartes, 1, MPI_INT, MPI_ROOT, juego_comm); int mus = 99; if ((modo == 'I' || modo == 'i') && siguienteJugador == jugadorHumano) { char c = 'Z'; printf("[maestro] Mano actual del jugador %d\n", jugadorHumano); recibirMazo(manoJugadorHumano, jugadorHumano, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); printMazo(manoJugadorHumano, N_CARTAS_MANO); printf("¿Hay mus? (S:mus, N:no mus):\n"); fflush(stdout); scanf(" %c", &c); getchar(); if (c == 'S' || c == 's') { mus = 0; } else { mus = 1; } fflush(stdout); fflush(stdin); MPI_Send(&mus, 1, MPI_INT, jugadorHumano, 0, juego_comm); }; MPI_Recv(&bufferRcv[0], 1, MPI_INT, siguienteJugador, 0, juego_comm, MPI_STATUS_IGNORE); MPI_Recv(&bufferRcv[1], 1, MPI_INT, siguienteJugador, 0, juego_comm, MPI_STATUS_IGNORE); MPI_Recv(&bufferRcv[2], 1, MPI_INT, siguienteJugador, 0, juego_comm, MPI_STATUS_IGNORE); jugadorMano = bufferRcv[0]; if (jugadorMano != 99) { printf("[maestro] Mus cortado por jugador: %d\n", jugadorMano); } turno++; if (jugadorMano == 99 || jugadorMano == 0 || jugadorMano == 1 || jugadorMano == 2 || jugadorMano == 3) { bufferSnd[0] = jugadorMano; } else { jugadorMano = 99; } if (bufferRcv[1] == 0 || bufferRcv[1] == 1 || bufferRcv[1] == 2 || bufferRcv[1] == 3) { siguienteJugador = bufferRcv[1]; bufferSnd[1] = siguienteJugador; } else { siguienteJugador = add_mod(siguienteJugador, 1, 4); bufferSnd[1] = siguienteJugador; } if (jugadorMano != 99) { siguienteJugador = jugadorMano; bufferSnd[1] = jugadorMano; } bufferSnd[2] = turno; MPI_Bcast(&bufferSnd, 3, MPI_INT, MPI_ROOT, juego_comm); } MPI_Bcast(&siguienteJugador, 1, MPI_INT, MPI_ROOT, juego_comm); } printf("[maestro] La mano es: %d\n", jugadorMano); int conteos[10]; int paresBuf[25]; int juegoBuf[5]; for (i = 0; i < 10; i++) { conteos[i] = 0; } int rbuf[50]; int rbufInv[50]; int envite[2]; int enviteAnterior[2]; envite[0] = 0; envite[1] = 0; enviteAnterior[0] = 0; enviteAnterior[1] = 0; int envites[10]; int enviteContraria[2]; enviteContraria[0] = 99; enviteContraria[1] = 0; int lances[N_LANCES]; int tienenPares[N_JUGADORES + 1]; int tienenJuego[N_JUGADORES + 1]; int hayPares = 0; int hayJuego = 0; //int pareja; //1 es pareja mano, 0 es pareja postre int j = 0; for (j = 0; j < N_LANCES + 1; j++) { /* envites */ //automático if (j == 2) { // ver si hay pares // recupera pares de los jugadores MPI_Gather(conteos, 1, MPI_INT, tienenPares, 1, MPI_INT, MPI_ROOT, juego_comm); // comprueba que alguno es distinto de cero for (i = 0; i < N_JUGADORES; i++) { if (tienenPares[i] != 0) { hayPares = 1; } } printf("HAY PARES: %d\n", hayPares); } if (j == 3) { // ver si hay juego // recupera pares de los jugadores MPI_Gather(conteos, 1, MPI_INT, tienenJuego, 1, MPI_INT, MPI_ROOT, juego_comm); // comprueba que alguno es distinto de cero for (i = 0; i < N_JUGADORES; i++) { if (tienenJuego[i] != 0) { hayJuego = 1; } } printf("HAY JUEGO: %d\n", hayJuego); MPI_Bcast(&hayJuego, 1, MPI_INT, MPI_ROOT, juego_comm); } // recibir envite de la mano if ((j == 0) || (j == 1) || ((j == 2) && (hayPares == 1)) || ((j == 3) && (hayJuego == 1)) || ((j == 4) && (hayJuego == 0))) { printf("[maestro] Se juega este lance\n"); if ((modo == 'I' || modo == 'i') && (siguienteJugador == jugadorHumano) && (jugadorHumano == jugadorMano)) { int e = 0; printf("[maestro] Mano actual del jugador %d\n", jugadorHumano); recibirMazo(manoJugadorHumano, jugadorHumano, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); printMazo(manoJugadorHumano, N_CARTAS_MANO); printf("Introduzca envite a %s: (0:no, 2: sí, >2: más)\n", lancesEtiquetas[j]); fflush(stdout); scanf(" %d", &e); getchar(); fflush(stdout); fflush(stdin); MPI_Send(&e, 1, MPI_INT, jugadorHumano, 0, juego_comm); } } MPI_Recv(&envite, 2, MPI_INT, jugadorMano, 0, juego_comm, MPI_STATUS_IGNORE); printf("[maestro]: Lance %d\n", j); enviteAnterior[0] = envite[0]; enviteAnterior[1] = envite[1]; printf("[maestro]: Envite de la mano: %d\n", envite[0]); // enviar envite a todos los jugadores MPI_Bcast(&envite, 2, MPI_INT, MPI_ROOT, juego_comm); if ((modo == 'I' || modo == 'i') && jugadorHumano != jugadorMano) { int e = 0; int humanoTienePares = 0; MPI_Recv(&humanoTienePares, 1, MPI_INT, jugadorHumano, 0, juego_comm, MPI_STATUS_IGNORE); if (humanoTienePares != 0) { printf("[maestro] Mano actual del jugador %d\n", jugadorHumano); recibirMazo(manoJugadorHumano, jugadorHumano, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); printMazo(manoJugadorHumano, N_CARTAS_MANO); printf("Introduzca envite a %s: (0:no, 2: sí, >2: más)\n", lancesEtiquetas[j]); fflush(stdout); scanf(" %d", &e); getchar(); fflush(stdout); fflush(stdin); MPI_Send(&e, 1, MPI_INT, jugadorHumano, 0, juego_comm); } } //rondas de envites hasta que se igualen o no se acepten // se garantiza que no va a haber repeticiones porque se van a rajar // recibir respuesta de todos los jugadores: de la pareja contraria, prima la más alta MPI_Gather(conteos, 10, MPI_INT, envites, 2, MPI_INT, MPI_ROOT, juego_comm); printf("[maestro] recibe envites\n"); if (ocurrenciasArray(envites, 8, 99) == 1) { ordago = 1; printf("¡¡¡ÓRDAGO!!!\n"); MPI_Bcast(&ordago, 1, MPI_INT, MPI_ROOT, juego_comm); break; }//ordago MPI_Bcast(&ordago, 1, MPI_INT, MPI_ROOT, juego_comm); apuestas[j] = calcularEnvite(envites, enviteAnterior, jugadorMano, piedras); printf("PIEDRAS MANO: %d\n", piedras[1]); printf("PIEDRAS POSTRE: %d\n", piedras[0]); // enviar respuesta de pareja contraria a todos los jugadores MPI_Bcast(&enviteContraria, 2, MPI_INT, MPI_ROOT, juego_comm); if (j == 3 && hayJuego == 1) { break; //no se juega al punto } } // } // almacenar envites /* Recepción de datos para evaluar las manos de los jugadores */ MPI_Gather(conteos, 10, MPI_INT, rbuf, 10, MPI_INT, MPI_ROOT, juego_comm); MPI_Gather(conteos, 10, MPI_INT, rbufInv, 10, MPI_INT, MPI_ROOT, juego_comm); MPI_Gather(conteos, 5, MPI_INT, paresBuf, 5, MPI_INT, MPI_ROOT, juego_comm); MPI_Gather(conteos, 1, MPI_INT, juegoBuf, 1, MPI_INT, MPI_ROOT, juego_comm); /*cálculo de manos*/ lances[0] = calculaGrande(rbuf, jugadorMano); lances[1] = calculaChica(rbufInv); lances[2] = calcularPares(paresBuf, jugadorMano); lances[3] = calcularJuego(juegoBuf, jugadorMano); printf("Mejor mano a grande: jugador %d\n", lances[0]); printf("Mejor mano a chica: jugador %d\n", lances[1]); printf("Mejor mano a pares: jugador %d\n", lances[2]); printf("Mejor mano a juego: jugador %d\n", lances[3]); if (ordago == 1) { printf("Ganador del lance %s y juego: jugador %d\n ", lancesEtiquetas[j], lances[j]); } /* for (i = 0; i < N_JUGADORES; i++) { if (paresBuf[5 * i] != 99) { printf("[jugador %d] Duples de la misma carta: %s\n", i, caras[paresBuf[5 * i]]); } else if (paresBuf[5 * i + 2] == 2) { printf("[jugador %d] DUPLES PAREJAS DE %s Y %s\n", i, caras[paresBuf[5 * i + 3]], caras[paresBuf[5 * i + 4]]); } else if (paresBuf[5 * i + 1] != 99) { printf("[jugador %d] MEDIAS DE: %s\n", i, caras[paresBuf[5 * i + 1]]); } else if (paresBuf[5 * i + 2] == 1) { printf("[jugador %d] PAREJA DE %s\n", i, caras[paresBuf[5 * i + 3]]); } } */ for (i = 0; i < N_JUGADORES; i++) { printf("JUEGO DE JUGADOR %d: %d\n", i, juegoBuf[i]); } for (i = 0; i <= N_LANCES; i++) { printf("APUESTA LANCE %d: %d\n", i, apuestas[i]); if (apuestas[i] != 0) { piedras[queParejaSoy(lances[i], jugadorMano)] += apuestas[i]; } } printf("PIEDRAS MANO: %d\n", piedras[1]); printf("PIEDRAS POSTRE: %d\n", piedras[0]); if (enQueParejaEstoy(jugadorMano) == 1) { pareja1[2] = piedras[1]; pareja2[2] = piedras[0]; } else { pareja1[2] = piedras[0]; pareja2[2] = piedras[1]; } pareja1[3] = pareja1[2] / N_PUNTOS_JUEGO; pareja2[3] = pareja2[2] / N_PUNTOS_JUEGO; pareja1[4] = pareja1[3] / N_JUEGOS_VACA; pareja2[4] = pareja2[3] / N_JUEGOS_VACA; pareja1[5] = pareja1[4] / N_VACAS_PARTIDA; pareja2[5] = pareja2[4] / N_VACAS_PARTIDA; recibirMazo(mano0, 0, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); recibirMazo(mano1, 1, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); recibirMazo(mano2, 2, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); recibirMazo(mano3, 3, juego_comm, N_CARTAS_MANO, MPI_STATUS_IGNORE); printf("MANO DEL JUGADOR 0:\n"); printMazo(mano0, N_CARTAS_MANO); printf("MANO DEL JUGADOR 1:\n"); printMazo(mano1, N_CARTAS_MANO); printf("MANO DEL JUGADOR 2:\n"); printMazo(mano2, N_CARTAS_MANO); printf("MANO DEL JUGADOR 3:\n"); printMazo(mano3, N_CARTAS_MANO); printf("PUNTUACIONES:\n"); printf("PAREJA 1\n"); printf("RONDA: %d\n", pareja1[2]); printf("JUEGO: %d\n", pareja1[3]); printf("VACA: %d\n", pareja1[4]); printf("PARTIDA: %d\n", pareja1[5]); printf("PAREJA 2\n"); printf("RONDA: %d\n", pareja2[2]); printf("JUEGO: %d\n", pareja2[3]); printf("VACA: %d\n", pareja2[4]); printf("PARTIDA: %d\n", pareja2[5]); /**************************************************************/ /* Terminan rondas /**************************************************************/ repartidor = jugadorMano; ronda++; if ((pareja1[5] == 1) || pareja2[5] == 1) { // fin de partida int finPartida = 1; MPI_Bcast(&finPartida, 1, MPI_INT, MPI_ROOT, juego_comm); } else { //sigue partida int finPartida = 0; MPI_Bcast(&finPartida, 1, MPI_INT, MPI_ROOT, juego_comm); } } MPI_Comm_disconnect(&juego_comm); MPI_Finalize(); return 0; }
SEXP Rhpc_mpi_initialize(void) { int *mpi_argc = (int *)&MPI_argc; char ***mpi_argv= (char ***)MPI_argv; int mpi_version = 0; int mpi_subversion = 0; #if defined(__ELF__) void *dlh = NULL; void *dls = NULL; int failmpilib; # ifdef HAVE_DLADDR Dl_info info_MPI_Init; int rc ; # endif #endif if(finalize){ warning("Rhpc were already finalized."); return(R_NilValue); } if(initialize){ warning("Rhpc were already initialized."); return(R_NilValue); } #if defined(__ELF__) if ( NULL != (dlh=dlopen(NULL, RTLD_NOW|RTLD_GLOBAL))){ if(NULL != (dls = dlsym( dlh, "MPI_Init"))) failmpilib = 0; /* success loaded MPI library */ else failmpilib = 1; /* maybe can't loaded MPI library */ dlclose(dlh); } if( failmpilib ){ # ifdef HAVE_DLADDR /* maybe get beter soname */ rc = dladdr((void *)MPI_Init, &info_MPI_Init); if (rc){ Rprintf("reload mpi library %s\n", info_MPI_Init.dli_fname ); if (!dlopen(info_MPI_Init.dli_fname, RTLD_GLOBAL | RTLD_LAZY)){ Rprintf("%s\n",dlerror()); } }else{ Rprintf("Can't get Information by dladdr of function MPI_Init,%s\n", dlerror()); } # else Rprintf("Can't get Information by dlsym of function MPI_Init,%s\n", dlerror()); # endif } #endif MPI_Get_version(&mpi_version, &mpi_subversion); if ( mpi_version >= 2){ mpi_argc=NULL; mpi_argv=NULL; } _M(MPI_Init(mpi_argc, mpi_argv)); _M(MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN)); _M(MPI_Comm_set_errhandler(MPI_COMM_SELF, MPI_ERRORS_RETURN)); _M(MPI_Comm_rank(MPI_COMM_WORLD, &MPI_rank)); _M(MPI_Comm_size(MPI_COMM_WORLD, &MPI_procs)); DPRINT("Rhpc_initialize : rank:%d size:%d\n", MPI_rank, MPI_procs); RHPC_Comm = MPI_COMM_WORLD; Rhpc_set_options( MPI_rank, MPI_procs,RHPC_Comm); if (MPI_rank == 0){ /* Master : get RhpcSpawn path*/ int errorOccurred=0; SEXP ret; SEXP cmdSexp, cmdexpr; ParseStatus status; PROTECT(cmdSexp = allocVector(STRSXP, 1)); SET_STRING_ELT(cmdSexp, 0, mkChar("system.file('RhpcSpawn',package='Rhpc')")); PROTECT( cmdexpr = R_ParseVector(cmdSexp, -1, &status, R_NilValue)); ret=R_tryEval(VECTOR_ELT(cmdexpr,0), R_GlobalEnv, &errorOccurred); strncpy(RHPC_WORKER_CMD, CHAR(STRING_ELT(ret,0)), sizeof(RHPC_WORKER_CMD)); UNPROTECT(2); } initialize = 1; return(R_NilValue); }
void IMB_make_sys_info() /* Prints to stdout some basic information about the system (outcome of the 'uname' command) */ { int dont_care, mpi_subversion, mpi_version; /* IMB 3.1 << */ #ifndef WIN_IMB struct utsname info; uname( &info ); dont_care = MPI_Get_version(&mpi_version,&mpi_subversion); fprintf(unit,"# Machine : %s\n",info.machine); fprintf(unit,"# System : %s\n",info.sysname); fprintf(unit,"# Release : %s\n",info.release); fprintf(unit,"# Version : %s\n",info.version); #else /* include WIN case */ OSVERSIONINFOEX info; TCHAR infoBuf[INFO_BUFFER_SIZE]; DWORD bufCharCount = INFO_BUFFER_SIZE; char *substr_ptr; dont_care = MPI_Get_version(&mpi_version,&mpi_subversion); info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); GetVersionEx((OSVERSIONINFO *) &info); bufCharCount = ExpandEnvironmentStrings("%PROCESSOR_IDENTIFIER%",infoBuf,INFO_BUFFER_SIZE); /* Replace "Intel64" by "Intel(R) 64" */ substr_ptr = strstr(infoBuf, "Intel64"); if( substr_ptr != NULL ) fprintf(unit,"# Machine : Intel(R) 64%s\n", substr_ptr+strlen("Intel64")); else { /* Replace "EM64T" by "Intel(R) 64" */ substr_ptr = strstr(infoBuf, "EM64T"); if( substr_ptr != NULL ) fprintf(unit,"# Machine : Intel(R) 64%s\n", substr_ptr+strlen("EM64T")); else fprintf(unit,"# Machine : %s\n",infoBuf); } if (info.dwMajorVersion == 4) switch (info.dwMinorVersion) { case 90 : fprintf(unit,"# System : Windows Me\n"); break; case 10 : fprintf(unit,"# System : Windows 98\n"); break; case 0 : fprintf(unit,"# System : Windows NT 4.0\n"); break; default : break; } else if (info.dwMajorVersion == 5) switch (info.dwMinorVersion) { case 2 : fprintf(unit,"# System : Windows 2003\n"); break; case 1 : fprintf(unit,"# System : Windows XP\n"); break; case 0 : fprintf(unit,"# System : Windows 2000\n"); break; default : break; } else if (info.dwMajorVersion == 6) switch (info.dwMinorVersion) { case 0 : if (info.wProductType == VER_NT_WORKSTATION) fprintf(unit,"# System : Windows Vista\n"); else fprintf(unit,"# System : Windows Server 2008\n"); break; default : break; } fprintf(unit,"# Release : %-d.%-d.%-d\n",info.dwMajorVersion, info.dwMinorVersion,info.dwBuildNumber); fprintf(unit,"# Version : %s\n",info.szCSDVersion); #endif /* >> IMB 3.1 */ fprintf(unit,"# MPI Version : %-d.%-d\n",mpi_version,mpi_subversion); fprintf(unit,"# MPI Thread Environment: "); #ifdef USE_MPI_INIT_THREAD switch (mpi_thread_environment) { case MPI_THREAD_SINGLE : fprintf(unit,"MPI_THREAD_SINGLE\n"); break; case MPI_THREAD_FUNNELED : fprintf(unit,"MPI_THREAD_FUNNELED\n"); break; case MPI_THREAD_SERIALIZED : fprintf(unit,"MPI_THREAD_SERIALIZED\n"); break; default : fprintf(unit,"MPI_THREAD_MULTIPLE\n"); break; } #endif // IMB 3.2 add on: Version information to stdout if( strcmp(VERSION,"3.2") >0 ) { fprintf(unit,"\n\n# New default behavior from Version 3.2 on:\n\n"); fprintf(unit,"\ # the number of iterations per message size is cut down \n\ # dynamically when a certain run time (per message size sample) \n\ # is expected to be exceeded. Time limit is defined by variable \n\ # \"SECS_PER_SAMPLE\" (=> IMB_settings.h) \n\ # or through the flag => -time \n\ "); }
int main(int argc, char *argv[]) { info = (struct test_info *)malloc(sizeof(struct test_info)); test_info_init(info); info->test_type = 0; msgCount = 50; info->msg_count=msgCount; struct plat_opts_config_mpilogme config; SDF_boolean_t success = SDF_TRUE; uint32_t numprocs; int tmp, namelen, mpiv = 0, mpisubv = 0; char processor_name[MPI_MAX_PROCESSOR_NAME]; int msg_init_flags = SDF_MSG_MPI_INIT; config.inputarg = 0; config.msgtstnum = 50; /* We may not need to gather anything from here but what the heck */ loadProperties("/opt/schooner/config/schooner-med.properties"); // TODO get filename from command line /* make sure this is first in order to get the the mpi init args */ success = plat_opts_parse_mpilogme(&config, argc, argv) ? SDF_FALSE : SDF_TRUE; printf("input arg %d msgnum %d success %d\n", config.inputarg, config.msgtstnum, success); fflush(stdout); myid = sdf_msg_init_mpi(argc, argv, &numprocs, &success, msg_init_flags); info->myid = myid; if ((!success) || (myid < 0)) { printf("Node %d: MPI Init failure... exiting - errornum %d\n", myid, success); fflush(stdout); MPI_Finalize(); return (EXIT_FAILURE); } tmp = init_msgtest_sm((uint32_t)myid); /* Enable this process to run threads across 2 cpus, MPI will default to running all threads * on only one core which is not what we really want as it forces the msg thread to time slice * with the fth threads that send and receive messsages * first arg is the number of the processor you want to start off on and arg #2 is the sequential * number of processors from there */ lock_processor(0, 2); info->lock_cpu = 2; /* Startup SDF Messaging Engine FIXME - dual node mode still - pnodeid is passed and determined * from the number of processes mpirun sees. */ sleep(1); msg_init_flags = msg_init_flags | SDF_MSG_RTF_DISABLE_MNGMT; sdf_msg_init(myid, &pnodeid, msg_init_flags); MPI_Get_version(&mpiv, &mpisubv); MPI_Get_processor_name(processor_name, &namelen); printf("Node %d: MPI Version: %d.%d Name %s \n", myid, mpiv, mpisubv, processor_name); fflush(stdout); plat_log_msg( PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: Completed Msg Init.. numprocs %d pnodeid %d Starting Test\n", myid, numprocs, pnodeid); info->pnodeid = pnodeid; for (msgCount = 0; msgCount < 2; msgCount++) { sleep(2); plat_log_msg(PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: Number of sleeps %d\n", myid, msgCount); } /* create the fth test threads */ fthInit(); // Init // start the message engine sdf_msg_startmsg(myid, 0, NULL); pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&fthPthread[0], &attr, &MixedthreadTestfthUniptlRoutine, &myid); pthread_create(&fthPthread[1], &attr, &MixedthreadTestpthreadUniptlRoutine, &myid); plat_log_msg(PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: Created pthread for mixed thread test2\n", myid); info->pthread_info = 2; info->fth_info = 6; pthread_join(fthPthread[0], NULL); pthread_join(fthPthread[1], NULL); plat_log_msg(PLAT_LOG_ID_INITIAL, LOG_CAT, PLAT_LOG_LEVEL_TRACE, "\nNode %d: SDF Messaging Test Complete\n", myid); sdf_msg_stopmsg(myid, SYS_SHUTDOWN_SELF); plat_shmem_detach(); info->success++; if (myid == 0) { sched_yield(); printf("Node %d: Exiting message test after yielding... Calling MPI_Finalize\n", myid); fflush(stdout); sched_yield(); MPI_Finalize(); print_test_info(info); test_info_final(info); } else { printf("Node %d: Exiting message test... Calling MPI_Finalize\n", myid); fflush(stdout); sched_yield(); MPI_Finalize(); } printf("Successfully ends\n"); return (EXIT_SUCCESS); }
void armci_mpi2_server_init() { int namelen, version, subversion; char processor_name[MPI_MAX_PROCESSOR_NAME]; long shm_info[3]; MPI_Status status; MPI_Comm_rank(ARMCI_COMM_WORLD, &armci_server_me); MPI_Comm_size(ARMCI_COMM_WORLD, &armci_nserver); MPI_Get_processor_name(processor_name, &namelen); MPI_Get_version(&version, &subversion); armci_mpi2_server_debug(armci_server_me, "I'm %d of %d SERVERS running on %s (MPI %d.%d)\n", armci_server_me, armci_nserver, processor_name, version, subversion); /* get parent's groupinfo */ MPI_Comm_get_parent(&MPI_COMM_SERVER2CLIENT); if (MPI_COMM_SERVER2CLIENT == MPI_COMM_NULL) { armci_die("mpi2_server: Invalid spawn. No parent process found.\n",0); } /* receive my clients info */ { int msg[3]; MPI_Recv(msg, 3, MPI_INT, MPI_ANY_SOURCE, ARMCI_MPI_SPAWN_INIT_TAG, MPI_COMM_SERVER2CLIENT, &status); if(msg[0]-ARMCI_MPI_SPAWN_INIT_TAG != armci_server_me) { armci_die("mpi2_server: Recv failed", msg[0]); } armci_client_first = msg[1]; armci_nclients = msg[2]; armci_mpi2_server_debug(armci_server_me, "My clients are [%d-%d]\n", armci_client_first, armci_client_first+armci_nclients-1); } /********************************************************************** * Emulate PARMCI_Init(). * Spawned Data server processes emulate PARMCI_Init() to complete the * ARMCI Initalization process similar to clients */ armci_clus_info =(armci_clus_t*)malloc(armci_nserver*sizeof(armci_clus_t)); if(armci_clus_info == NULL) { armci_die("mpi2_server: armci_clus_info malloc failed", 0); } /* receive and emulate clus info, lock info */ MPI_Recv(armci_clus_info, armci_nserver*sizeof(armci_clus_t), MPI_BYTE, armci_client_first, ARMCI_MPI_SPAWN_INIT_TAG, MPI_COMM_SERVER2CLIENT, &status); MPI_Recv(shm_info, 3, MPI_LONG, armci_client_first, ARMCI_MPI_SPAWN_INIT_TAG, MPI_COMM_SERVER2CLIENT, &status); /* server setup clusinfo&locks, exactly as this node's armci master */ emulate_armci_init_clusinfo(); /* armci_init_clusinfo() in PARMCI_Init */ emulate_armci_allocate_locks(shm_info); /* armci_allocate_locks() */ /* Fence data structures should be initialized by server too. see * armci_generic_rmw (called by armci_server_rmw) */ armci_init_fence(); /** * End of PARMCI_Init() emulation. * *******************************************************************/ MPI_Barrier(ARMCI_COMM_WORLD); }