/** * Main function */ int main() { // We create a condition CondId cond = CondCreate("TableCondition"); // We create a thread to fill it and one to read it ThreadId thread_fill = newThread("FillThread", (int)fillThread, (int)cond); ThreadId thread_read = newThread("ReadThread", (int)readThread, (int)cond); // Wait the two threads before returning if (Join(thread_fill) < 0) n_printf("Error joining first thread"); n_printf("Thread fill just finished"); if (Join(thread_read) < 0) n_printf("Error joining second thread"); n_printf("Thread read just finished"); // Delete the condition if (CondDestroy(cond) < 0) n_printf("Error destroy lock"); // Exit the program return 0; }
int main(int argc, char** argv) { recyclr = newLL(); inQ = newLL(); timeQ = newLL(); ArgRead ar = {'\n', stdin}; ArgTime at = {CLOCK_MONOTONIC}; ArgPrint ap = {'\n', stdout}; // Run the program Thread *tr = newThread(NULL, thr_read, &ar), *tt = newThread(NULL, thr_time, &at); thr_print(&ap); // We exit soon, still run deletion, // to clean up possible FDs and do some // error checking deleteThread(tr); deleteThread(tt); deleteLL(recyclr); deleteLL(inQ); deleteLL(timeQ); return 0; }
HANDLE * zeroWriter_new(int * value){ HANDLE * consumers = malloc(sizeof(HANDLE) * 2); consumers[0] = newThread(ZeroWriter, &value); consumers[1] = newThread(ZeroWriter, &value); return consumers; }
/** main thread -- parent **/ int main() { tcb_t *tid1, *tid2; startThreadSystem(); /* Create user threads */ tid1= newThread(sub1); tid2= newThread(sub2); printf("Waiting on tid1\n"); fflush(stdout); twait(tid1); printf("Waiting on tid2\n"); fflush(stdout); twait(tid2); printf("Main done\n"); exit(0); }
/** main **/ int main() { int ndx; mystack_t *stack1; mystack_t *stack2; startThreadSystem(); /* Create stack1 */ stack1 = newStack(100); /* And exercise it by spawning 4 threads */ for (ndx=0; ndx<4; ndx++) { parm[ndx].myID = ndx; parm[ndx].numWords = 30000; parm[ndx].stack = stack1; if ((ndx%2) == 0) { id[ndx] = newThread(pusher); } else { id[ndx] = newThread(popper); } } /* Create stack2 */ stack2 = newStack(5000); /* And exercise it by spawning 6 threads */ for (; ndx<10; ndx++) { parm[ndx].myID = ndx; parm[ndx].numWords = 9000; parm[ndx].stack = stack2; if ((ndx%2) == 0) { id[ndx] = newThread(pusher); } else { id[ndx] = newThread(popper); } } /* Wait for everyone to end */ for (ndx=0; ndx<10; ndx++) { twait(id[ndx]); if ((ndx % 2) == 1) { printf("Popper %d count = %d\n", ndx, parm[ndx].popcount); } } printf("Main thread done\n"); exit(0); }
void listener() { int channel,rcvid,returncode; msgpass * msg = malloc(sizeof(msgpass)); channel = makeChanP("/sys/taskbar"); while(1) { rcvid = recvMsg(channel,(void *)&msg); switch(msg->code) { case TSKM_KILLED: case TSKM_NEWITEM: case TSKM_MINIMIZED: case TSKM_INFOCUS: case TSKM_INBLUR: newThread(updateitem,STACK_DFL,msg); returncode = 0; break; case IO_OPEN: if(*(int *) (((char *)msg)+6) & (O_PROC|O_STAT)) returncode = makeCon(rcvid,1); else returncode = -1; break; } replyMsg(rcvid,returncode); } }
/** * Starts a thread that will terminate the program after the specified duration elapses. */ void TimeoutWatchdog::start(unsigned timeout_sec) { this->timeout_sec = timeout_sec; if(timeout_sec > 0) { boost::thread newThread(boost::bind(&TimeoutWatchdog::threadProc, this)); watchdogThread.swap(newThread); } }
/** Main thread **/ int main() { tcb_t *tid1, *tid2, *tid3, *tid4; /* Start the child threads running, and wait for them to complete */ startThreadSystem(); tid1 = newThread(sub1); tid2 = newThread(sub2); tid3 = newThread(sub3); tid4 = newThread(sub4); twait(tid1); twait(tid2); twait(tid3); twait(tid4); /* All threads have finished */ printf("Main done\n"); exit(0); }
void main(int argc, char *argv[]) { int ch; FILE *stream; struct termios T1; unsigned int baud=0; long brate,min=1000000,dif; while ((ch = getopt(argc, argv, "b:")) != EOF) { switch(ch) { case 'b': brate = strtol(optarg, NULL, 0); ch = 0; while (ch<11) { dif = bauds[ch] - brate; if (dif<0) dif = -dif; if (dif<min) { baud = ch; min = dif; } ch++; } break; } } if (argc-optind<1) { fprintf(stderr, "Usage: term [-b baudrate] device\nE.g. term /dev/modem\n"); exit(1); } stream = fopen(argv[optind],"rb"); if (!stream) { perror("term"); exit(1); } gettio(fileno(stream),&T1); T1.flags = TF_OPOST|TF_IGNCR; if (baud) T1.Speed = baud; settio(fileno(stream),&T1); gettio(STDIN_FILENO,&T1); T1.flags &= ~(TF_ICANON|TF_ECHO|TF_ICRLF); settio(STDIN_FILENO,&T1); globsock = fileno(stream); newThread(fromServer,256,&globsock); stream->_flags |= _IOBUFEMP; while(!feof(stream)) { while ((ch = fgetc(stream)) != EOF) putchar(ch); fflush(stdout); } }
int docommand(char *from, char *command, char *params, char **who, char **what) { char *ctcp; if (!strcmp(command,"QUIT")) { getwhat(params, what); return QUIT; } else if (!strcmp(command,"NICK")) { getwhat(params, what); return NICK; } else if (!strcmp(command,"PART")) { getwhat(params, what); return PART; } else if (!strcmp(command,"JOIN")) { getwhat(params, what); return JOIN; } else if (!strcmp(command,"NOTICE")) { getwhowhat(params, who, what); return NOTICE; } else if (!strcmp(command,"MODE")) { getwhowhat(params, who, what); return MODE; } else if (!strcmp(command,"PRIVMSG")) { getwhowhat(params, who, what); ctcp = *what; if (*ctcp == 1) { ctcp++; if (!strncmp(ctcp,"VERSION",7)) { sendChan(channel, SRVMSG, 3,"NOTICE ", from, " :\1VERSION " VERSIONREPLY "\1"); sendChan(channel, SCRMSG, "Someone versioned us :%s", from); return IGNORE; } else if (!strncmp(ctcp,"ACTION",6)) { *what = ctcp + 7; return ME; } else if (!strncmp(ctcp,"PING",4)) { sendChan(channel, SRVMSG, 4,"NOTICE ", from, " :\1PING ", ctcp+5); return IGNORE; } else if (!strncmp(ctcp,"DCC",3)) { //badness... auto receive the DCC. newThread(receivedcc,STACK_DFL,strdup(ctcp)); return DCC; } else { *what = ctcp; return UNKCTCP; } } return NORMAL; } else if (!strcmp(command,"PING")) { sendChan(channel, SRVMSG, 2,"PONG ",params); return IGNORE; } *what = params; return NORMAL; }
void Processor::start(JNIEnv *jniEnv) { std::cout << "Start\n"; jthread thread = newThread(jniEnv); jvmtiStartFunction callback = [](jvmtiEnv *jvmti_env, JNIEnv *jni_env, void *arg) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); Processor *processor = (Processor *) arg; processor->run(); }; jvmti_->RunAgentThread(thread, callback, this, JVMTI_THREAD_NORM_PRIORITY); }
void main(int argc, char *argv[]) { FILE *stream; char *server = argv[1]; int i; if (argc>1) { printf("Welcome to A-Jirc V1.0\n"); if (!strchr(server, '/')) { char *newserve = malloc(strlen(server)+16); sprintf(newserve, "/dev/tcp/%s:6667", server); server = newserve; } stream = fopen(server, "r"); if (!stream) { perror("AJirc"); exit(1); } if (argc>2) nick = argv[2]; con_init(); printf("Connected to server\n"); con_update(); con_setscroll(0,con_ysize-2); con_gotoxy(0,con_ysize-2); printf("Ajirc V1.0 (c) J Maginnis & A Greenwood"); for (i=39; i<con_xsize; i++) { putchar('-'); } channel = makeChan(); globsock = dup(fileno(stream)); newThread(fromUser,STACK_DFL,NULL); newThread(outThread,256,&globsock); while (process(stream)); printf("Connection closed by remote host!\n"); con_end(); printf("\x1b[0m\x1b[H\x1b[2J"); exit(1); } printf("\x1b[0m\x1b[H\x1b[2J"); }
void setThreadNumber(Server* server, int nthreads) { assert(server != NULL && nthreads > 0 && nthreads < 100); server->threads = (struct WorkerThread**)malloc(nthreads * sizeof(struct WorkerThread*)); assert(server->threads != NULL); int i; for(i = 0; i < nthreads; i++) { server->threads[i] = newThread(); server->threads[i]->server = server; } server->nthreads = nthreads; }
int mainBecomesThread(){ ucontext_t *uc = (ucontext_t*)malloc(sizeof(ucontext_t)); MAIN_THREAD = newThread(getNextTID(), STATUS_READY, uc); if(!(uc && MAIN_THREAD)) return -1; MAIN_IS_THREAD = TRUE; setRunningThread(MAIN_THREAD); #ifdef O_PREEMPTION static int hasBeenCalled = 0; if (!hasBeenCalled) scheduler(); hasBeenCalled = 1; #endif return 0; }
/** * Open a file and set it as the current listened file. */ void MainWindow::setCurrentFile(QString file) { this->closeCurrentFile(); disconnect(&this->model, SIGNAL(newLogEntries(int)), 0, 0); this->currentFile = new QFile(this->currentDir.absolutePath() + '/' + file); if (currentFile->exists() && this->currentFile->open(QIODevice::ReadOnly)) { this->model.setDataSource(this->currentFile); this->refreshFilters(); // New messages can be logged after the file is loaded, thus some new severities/modules/threads can appear. connect(&this->model, SIGNAL(newSeverity(QString)), this->severities, SLOT(addItem(const QString&))); connect(&this->model, SIGNAL(newModule(QString)), this->modules, SLOT(addItem(const QString&))); connect(&this->model, SIGNAL(newThread(QString)), this->threads, SLOT(addItem(const QString&))); this->ui->tblLog->scrollToBottom(); connect(&this->model, SIGNAL(newLogEntries(int)), this, SLOT(newLogEntries(int))); }
void initEventManager(void) { UInt32 i; kEventRead = 0; kEventWrite = 0; initSList(&kEventRegisters); for(i=0;i<EVENT_MAX;i++) { kEvents[i].time = 0; kEvents[i].id = 0; kEvents[i].message = 0; } // event manager thread is set with a high priority kEventThread = newThread(&kEventThreadManager,EVENT_THREAD_STACK_SIZE,EVENT_THREAD_CPU_TIME,EVENT_THREAD_PRIORITY); }
void makecbutton() { void * clickbmpclass, * cbut; MenuData * mainmenu; clickbmpclass = JSubclass(&JBmpClass,-1, METHOD(MJW, Button), opencmenu, -1); cbut = JNew(clickbmpclass); JBmpInit(cbut,16,16,cbuticon); ((JW*)cbut)->Sense |= WEV_Button; mainmenu = getmenudir("/wings/"); JWSetData(cbut,mainmenu); resizebar(1); JCntAdd(taskbar,cbut); JWinShow(cbut); sendChan(appchannel,REFRESH); newThread(getrunningapps,STACK_DFL,NULL); }
/* * loadProg - load the task to sample */ static void loadProg( char *exe, char *cmdline ) { STARTUPINFO sinfo; PROCESS_INFORMATION pinfo; int rc; memset( &sinfo, 0, sizeof( sinfo ) ); sinfo.cb = sizeof( sinfo ); // set ShowWindow default value for nCmdShow parameter sinfo.dwFlags = STARTF_USESHOWWINDOW; sinfo.wShowWindow = SW_SHOWNORMAL; rc = CreateProcess( NULL, /* application name */ cmdline, /* command line */ NULL, /* process attributes */ NULL, /* thread attributes */ FALSE, /* inherit handles */ DEBUG_ONLY_THIS_PROCESS, /* creation flags */ NULL, /* environment block */ NULL, /* starting directory */ &sinfo, /* startup info */ &pinfo /* process info */ ); if( !rc ) { internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] ); } rc = WaitForDebugEvent( &debugEvent, INFINITE ); if( !rc || (debugEvent.dwDebugEventCode != CREATE_PROCESS_DEBUG_EVENT) || (debugEvent.dwProcessId != pinfo.dwProcessId) ) { internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] ); } taskPid = debugEvent.dwProcessId; processHandle = debugEvent.u.CreateProcessInfo.hProcess; newThread( debugEvent.dwThreadId, debugEvent.u.CreateProcessInfo.hThread ); codeLoad( debugEvent.u.CreateProcessInfo.hFile, (DWORD) debugEvent.u.CreateProcessInfo.lpBaseOfImage, exe, SAMP_MAIN_LOAD ); } /* loadProg */
void thread::start() { lock(); if (started()) { unlock(); throw thread_already_started(); } try { iState = Starting; if (!iUsingExistingThread) { thread_object_pointer newThread(new boost::thread(boost::bind(&thread::entry_point, this))); iThreadObject = newThread; unlock(); } else { unlock(); entry_point(); } } catch(const std::exception& aException) { iState = Error; unlock(); std::cerr << std::string("Error starting thread due to exception being thrown (") + aException.what() + ")." << std::endl; throw; } catch(...) { iState = Error; unlock(); std::cerr << std::string("Error starting thread due to exception of unknown type being thrown.") << std::endl; throw; } }
void bootstrap(char * entry, char * bootPkg, char * version) { char errorMsg[MAX_MSG_LEN]; defineExitProg(); defineDieProg(); // defineTrapProg(); // defineObjectProg(kmain); defineResumeProgs(); /* define the resume entry points */ ptrI mainThread = newThread(); processPo root = rootProcess(mainThread, bootPkg); // We create the root with a early death code - updated later switch (loadPackage(bootPkg, version, errorMsg, NumberOf(errorMsg), NULL)) { default: logMsg(logFile, "corrupt or no boot package found in %s:%s", bootPkg, errorMsg); lo_exit(EXIT_FAIL); return; case Eof: logMsg(logFile, "short boot package %s", bootPkg); lo_exit(EXIT_FAIL); return; case Ok: { ptrI prog = newProgramLbl(entry, 0); if (!IsProgram(prog)) { logMsg(logFile, "%U entry point not found", entry); lo_exit(EXIT_FAIL); } else { root->proc.PROG = ProgramOf(prog); /* this is where we establish the program */ root->proc.PC = FirstInstruction(root->proc.PROG); root->proc.thread = kmainThread; runGo(root); } } } }
int thread_create(thread_t*t,void*(*func)(void *),void*arg){ #ifdef O_PREEMPTION interruptsOff(); #endif //si le main n'est pas un thread, il le devient sinon if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1) return -1; //on cree le context du thread ucontext_t *uc = createContext((void (*) (void))func,arg); if(uc == NULL) return -1; //on cree le thread *t = getNextTID(); thread *newth = newThread(*t, STATUS_READY, uc); //on met à jour la rélation thread pere et thread fils thread* pere = getRunningThread(); pere->is_father = TRUE; newth->father = pere; newth->context->uc_link = pere->context; addInFifo(pere); #ifdef O_PRIORITE updatePriority(pere); #endif //on lance le nouveau thread cree setRunningThread(newth); #ifdef O_PREEMPTION interruptsOn(); #endif swapcontext(pere->context, newth->context); return 0; }
int usermain(void) { setGpioDirection(GPIO0_7,GPIO_OUT); //led // Initialize uart0 and set debugger interface initUART0(); setDebugInterface(sendByteToUART0); debugPrintf("lpc13xx is running !\r\n"); // Power down usb clock SETBIT(LPC_SYSCON->PDRUNCFG,10); SETBIT(LPC_SYSCON->PDRUNCFG,8); newThread(led,512,10,5); // newThread(PRS_I2CComm,512,10,4); return 0; }
/** startThreadSystem **/ void startThreadSystem() { runningTCB = &mainTCB; /* If create the ready and live lists */ if (readyList == NULL) { readyList = createList(); } if (liveList == NULL) { liveList = createList(); } if (suspendReadyList == NULL) { suspendReadyList = createList(); } /* Initialize action structure for vt alarm signal */ vtSigNum = SIGVTALRM; vtAlrmAction.sa_handler = timeslice; sigemptyset(&vtAlrmAction.sa_mask); vtAlrmAction.sa_flags = SA_NODEFER; /* Setup the tcleaner thread */ zombieList = createList(); newThread(tcleaner); }
dtNavMesh* buildMesh(InputGeom* geom, WCellBuildContext* wcellContext, int numCores) { dtNavMesh* mesh = 0; if (!geom || !geom->getMesh()) { CleanupAfterBuild(); wcellContext->log(RC_LOG_ERROR, "buildTiledNavigation: No vertices and triangles."); return 0; } mesh = dtAllocNavMesh(); if (!mesh) { CleanupAfterBuild(); wcellContext->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate navmesh."); return 0; } // setup some default parameters rcConfig cfg; memset(&cfg, 0, sizeof(rcConfig)); const float agentHeight = 2.1f; // most character toons are about this tall const float agentRadius = 0.6f; // most character toons are about this big around const float agentClimb = 1.0f; // character toons can step up this far. Seems ridiculously high ... const float tileSize = 1600.0f/3.0f/16.0f; // The size of one chunk cfg.cs = 0.1f; // cell size is a sort of resolution -> the bigger the faster cfg.ch = 0.05f; // cell height -> distance from mesh to ground, if too low, recast will not build essential parts of the mesh for some reason cfg.walkableSlopeAngle = 50.0f; // max climbable slope, bigger values won't make much of a change cfg.walkableHeight = (int)ceilf(agentHeight/cfg.ch);// minimum space to ceiling cfg.walkableClimb = (int)floorf(agentClimb/cfg.ch); // how high the agent can climb in one step cfg.walkableRadius = (int)ceilf(agentRadius/cfg.cs);// minimum distance to objects cfg.tileSize = (int)(tileSize/cfg.cs + 0.5f); cfg.maxEdgeLen = cfg.tileSize/2;; cfg.borderSize = cfg.walkableRadius + 3; cfg.width = cfg.tileSize + cfg.borderSize*2; cfg.height = cfg.tileSize + cfg.borderSize*2; cfg.maxSimplificationError = 1.3f; cfg.minRegionArea = (int)rcSqr(8); // Note: area = size*size cfg.mergeRegionArea = (int)rcSqr(20); // Note: area = size*size cfg.maxVertsPerPoly = 3; cfg.detailSampleDist = cfg.cs * 9; cfg.detailSampleMaxError = cfg.ch * 1.0f; // default calculations - for some reason not included in basic recast const float* bmin = geom->getMeshBoundsMin(); const float* bmax = geom->getMeshBoundsMax(); int gw = 0, gh = 0; rcCalcGridSize(bmin, bmax, cfg.cs, &gw, &gh); const int ts = cfg.tileSize; const int tw = (gw + ts-1) / ts; const int th = (gh + ts-1) / ts; // Max tiles and max polys affect how the tile IDs are caculated. // There are 22 bits available for identifying a tile and a polygon. int tileBits = rcMin((int)ilog2(nextPow2(tw*th)), 14); if (tileBits > 14) tileBits = 14; int polyBits = 22 - tileBits; int maxTiles = 1 << tileBits; int maxPolysPerTile = 1 << polyBits; dtNavMeshParams params; rcVcopy(params.orig, geom->getMeshBoundsMin()); params.tileWidth = cfg.tileSize * cfg.cs; params.tileHeight = cfg.tileSize * cfg.cs; params.maxTiles = maxTiles; params.maxPolys = maxPolysPerTile; dtStatus status; status = mesh->init(¶ms); if (dtStatusFailed(status)) { CleanupAfterBuild(); wcellContext->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init navmesh."); return 0; } // start building const float tcs = cfg.tileSize*cfg.cs; wcellContext->startTimer(RC_TIMER_TEMP); TileAdder Adder; dispatcher.Reset(); dispatcher.maxHeight = th; dispatcher.maxWidth = tw; int numThreads = 0; numThreads = std::min(2*numCores, 8); boost::thread *threads[8]; for(int i = 0; i < numThreads; ++i) { QuadrantTiler newTiler; newTiler.geom = geom; newTiler.cfg = cfg; newTiler.ctx = *wcellContext; boost::thread newThread(boost::ref(newTiler)); threads[i] = &newThread; } Adder.mesh = mesh; Adder.numThreads = numThreads; boost::thread AdderThread(boost::ref(Adder)); AdderThread.join(); // Start the build process. wcellContext->stopTimer(RC_TIMER_TEMP); return mesh; }
/* * StartProg - start sampling a program */ void StartProg( const char *cmd, const char *prog, char *full_args, char *dos_args ) { DWORD code; DWORD tid; CONTEXT con; BOOL waiting_for_first_bp; DWORD continue_how; BOOL rc; DWORD ttid; HANDLE tth; uint_32 Fir; /* unused parameters */ (void)cmd; strcpy( utilBuff, prog ); strcat( utilBuff, " " ); strcat( utilBuff, full_args ); loadProg( prog, utilBuff ); tid = debugEvent.dwThreadId; tth = CreateThread( NULL, 2048, TimerThread, NULL, 0, &ttid ); if( !tth ) { internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] ); } /* Attempt to ensure that we can record our samples in one shot */ SetThreadPriority( tth, THREAD_PRIORITY_TIME_CRITICAL ); Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] ); Output( prog ); Output( "\r\n" ); waiting_for_first_bp = TRUE; continue_how = DBG_CONTINUE; for( ;; ) { ContinueDebugEvent( taskPid, tid, continue_how ); rc = WaitForDebugEvent( &debugEvent, INFINITE ); continue_how = DBG_CONTINUE; tid = debugEvent.dwThreadId; switch( debugEvent.dwDebugEventCode ) { case EXCEPTION_DEBUG_EVENT: code = debugEvent.u.Exception.ExceptionRecord.ExceptionCode; switch( code ) { case STATUS_SINGLE_STEP: if( timeOut ) { myGetThreadContext( tid, &con ); Fir = LODWORD( con.Fir ); RecordSample( Fir, SEGMENT, tid ); timeOut = FALSE; } break; case STATUS_BREAKPOINT: /* Skip past the breakpoint in the startup code */ if( waiting_for_first_bp ) { SkipBreakpoint( tid ); waiting_for_first_bp = FALSE; } break; case STATUS_DATATYPE_MISALIGNMENT: case STATUS_ACCESS_VIOLATION: case STATUS_IN_PAGE_ERROR: case STATUS_NO_MEMORY: case STATUS_ILLEGAL_INSTRUCTION: case STATUS_NONCONTINUABLE_EXCEPTION: case STATUS_INVALID_DISPOSITION: case STATUS_ARRAY_BOUNDS_EXCEEDED: case STATUS_FLOAT_DENORMAL_OPERAND: case STATUS_FLOAT_DIVIDE_BY_ZERO: case STATUS_FLOAT_INVALID_OPERATION: case STATUS_FLOAT_OVERFLOW: case STATUS_FLOAT_STACK_CHECK: case STATUS_FLOAT_UNDERFLOW: case STATUS_INTEGER_DIVIDE_BY_ZERO: case STATUS_INTEGER_OVERFLOW: case STATUS_PRIVILEGED_INSTRUCTION: case STATUS_STACK_OVERFLOW: case STATUS_CONTROL_C_EXIT: if( debugEvent.u.Exception.dwFirstChance ) { continue_how = DBG_EXCEPTION_NOT_HANDLED; } else { Output( MsgArray[MSG_SAMPLE_4 - ERR_FIRST_MESSAGE] ); Output( "\r\n" ); doneSample = TRUE; TerminateProcess( processHandle, 0 ); report(); return; } break; default: continue_how = DBG_EXCEPTION_NOT_HANDLED; break; } break; case LOAD_DLL_DEBUG_EVENT: if( GetDllName( &debugEvent.u.LoadDll, utilBuff, sizeof( utilBuff ) ) ) { codeLoad( debugEvent.u.LoadDll.hFile, (DWORD) debugEvent.u.LoadDll.lpBaseOfDll, utilBuff, SAMP_CODE_LOAD ); } break; case CREATE_THREAD_DEBUG_EVENT: newThread( debugEvent.dwThreadId, debugEvent.u.CreateThread.hThread ); break; case EXIT_THREAD_DEBUG_EVENT: deadThread( debugEvent.dwThreadId ); break; case EXIT_PROCESS_DEBUG_EVENT: doneSample = TRUE; // TerminateProcess( processHandle, 0 ); - already gone!! report(); return; } } } /* StartProg */
int main(int argc, char *argv[]) { int returnVal = 0; CommandLineParser cLineParser; // Add all of the parameters we need std::string pedigreeFileName, genotypeFileName, lociFileName, outDirectory, printList; unsigned int numberOfRuns, numberOfThreads; bool printHelp = false; cLineParser.addArg("pedigree", &pedigreeFileName); cLineParser.addArg("genotype", &genotypeFileName); cLineParser.addArg("loci", &lociFileName); cLineParser.addArg("numberOfRuns", &numberOfRuns); cLineParser.addArg("numberOfThreads", &numberOfThreads, 1u); cLineParser.addArg("help", &printHelp, false); cLineParser.addArg(std::string("out"), &outDirectory, std::string(".")); cLineParser.addArg(std::string("print"), &printList, std::string()); // Now parse the input cLineParser.parse(argc, argv); cLineParser.setSingleValue("help"); // First check if we asked for help printing if (printHelp) { std::string errorMessage = "Input syntax is options and values or flags. Options are specified with -<option> -<value>, and flags with --<flag>. Available options are, \n"; auto addCommandLineOptSpec = [&](std::string option, std::string meaning) { errorMessage += "\t-" + option + " = " + meaning + "\n"; }; auto addCommandLineFlagSpec = [&](std::string option, std::string meaning) { errorMessage += "\t--" + option + " = " + meaning + "\n"; }; addCommandLineOptSpec("pedigree", "The path to the pedigree file to use."); addCommandLineOptSpec("genotype", "The path to the founder genotypes file to use."); addCommandLineOptSpec("loci", "The path to the loci file to use."); addCommandLineOptSpec("numberOfRuns", "The number of simulations to carry out for this dataset."); addCommandLineOptSpec("numberOfThreads", "The number of threads to use for simulations."); addCommandLineOptSpec("out", "The directory to output the results to."); addCommandLineOptSpec("print", "A comma-separated list of which generations to produce output for."); errorMessage += "Available flags are, \n"; addCommandLineFlagSpec("help", "Print help message for the program."); std::cout << errorMessage << std::endl; return 0; } // Parse which generations to print cLineParser.setSingleValue("print"); std::vector<std::string> generationsToPrint; if (!printList.empty()) { // Parse out the individual values std::string generation; bool stripWhiteSpace = true; const char sep = ','; for (auto character : printList) { if (character == sep) { if (!generation.empty()) { generationsToPrint.push_back(generation); } generation = ""; stripWhiteSpace = true; } else { if (stripWhiteSpace && std::isspace((unsigned char)character)) continue; // Otherwise a legit character stripWhiteSpace = false; generation.push_back(character); } } if (!generation.empty()) generationsToPrint.push_back(generation); } // TODO: Put input verification in // Check for any errors bool shouldExit = false; if (auto errors = cLineParser.errorsEncountered()) { std::cout << "Error in parsing input: " << std::endl; for (auto message : errors.value()) { std::cout << message << std::endl; } shouldExit = true; } if (auto warnings = cLineParser.warningsEncountered()) { std::cout << "Warnings generated when parsing input: " << std::endl; for (auto message : warnings.value()) { std::cout << message << std::endl; } } if (shouldExit) { return 1; } cLineParser.setAllValues(); // Then set up an appropriate simulation state SimulationManager simManager; try { simManager.build(pedigreeFileName, lociFileName, genotypeFileName); } catch (std::exception& e) { std::cout << e.what() << std::endl; return 1; } // TODO: Verify the input //Maybe<std::string> error = simManager.verifySimulationPrototype(); //if (error) //{ // // Push out any error message // std::cerr << error.value() << std::endl; // returnVal = 1; //} // TODO: This should be done elsewhere volatile unsigned int numberOfRunsComplete = 0; volatile unsigned int numberOfRunningThreads = 0; TimeHandler timeHandler; std::mutex outputMutex; std::mutex threadExceptionMutex; std::map<unsigned int, std::exception_ptr> threadExceptions; unsigned int exceptionPtrCounter = 0; try { const std::string outputFileName = (outDirectory.empty() ? outDirectory : outDirectory + "/") + "Output(" + timeHandler.getCurrentTimeStamp() + ").csv"; int reportEvery = 50; threadExceptionMutex.lock(); threadExceptions[exceptionPtrCounter] = nullptr; threadExceptionMutex.unlock(); ++exceptionPtrCounter; auto runAndWrite = [&, exceptionPtrCounter]() { try { auto result = simManager.getRealisation(); OutputMaker out; { std::lock_guard<std::mutex> guard(outputMutex); if (out.open(outputFileName, numberOfRunsComplete)) { if (generationsToPrint.size() > 0) out.printOnlyCertainGenerations(generationsToPrint); out << result; if (numberOfRunsComplete % reportEvery == 0 || numberOfRunsComplete == numberOfRuns - 1) { std::cout << "Done " << numberOfRunsComplete + 1 << " runs out of " << numberOfRuns << std::endl; } out.close(); } ++numberOfRunsComplete; } } catch (std::exception&) { threadExceptionMutex.lock(); threadExceptions[exceptionPtrCounter] = std::current_exception(); threadExceptionMutex.unlock(); --numberOfRunningThreads; return; } threadExceptionMutex.lock(); threadExceptions.erase(exceptionPtrCounter); threadExceptionMutex.unlock(); --numberOfRunningThreads; }; while (numberOfRunsComplete < (unsigned int)numberOfRuns) { if (numberOfRunningThreads < numberOfThreads) { // Make sure nothing has broken threadExceptionMutex.lock(); for (const auto& kv : threadExceptions) { if (kv.second != nullptr) { std::rethrow_exception(kv.second); } } threadExceptionMutex.unlock(); ++numberOfRunningThreads; std::thread newThread(runAndWrite); newThread.detach(); } } } catch (std::exception& e) { std::cout << e.what() << std::endl; return 1; } // Exit cleanly return returnVal; }
void main(int argc, char * argv[]) { void *appl; int type,rcvid,icocol; char * msg; void * but; rcvid = open("/sys/taskbar",O_PROC); if(rcvid != -1) { printf("Taskbar is already running!\n"); exit(1); } appchannel = makeChan(); appl = JAppInit(NULL,appchannel); //default position is at top of screen position = TSKM_ONTOP; if(argc > 1) { if(!strcmp(argv[1],"left")) position = TSKM_ONLEFT; else if(!strcmp(argv[1],"right")) position = TSKM_ONRIGHT; else if(!strcmp(argv[1],"top")) position = TSKM_ONTOP; else if(!strcmp(argv[1],"bottom")) position = TSKM_ONBOTTOM; } taskbar = JCntInit(NULL); if(position == TSKM_ONTOP || position == TSKM_ONBOTTOM) { ((JCnt*)taskbar)->Orient = JCntF_LeftRight; JWSetBounds(taskbar,0,0,0,16); } else { ((JCnt*)taskbar)->Orient = JCntF_TopBottom; JWSetBounds(taskbar,0,0,16,0); } JWndSetProp(taskbar); JAppSetMain(appl,taskbar); JWinShow(taskbar); newThread(makecbutton,STACK_DFL,NULL); retexit(0); newThread(listener,STACK_DFL,NULL); while(1) { rcvid = recvMsg(appchannel,(void *)&msg); type = *(int *)msg; //printf("got appchannel msg: #%d\n",type); switch(type) { case WIN_EventRecv: JAppDrain(appl); break; case REFRESH: JWinLayout(taskbar); break; case SETCOL: but = *(void **)(msg+2); icocol = *(int *)(msg+6); memset(((JBmp*)but)->Cols,icocol,4); /* ((JBmp*)but)->Cols[0] = icocol; ((JBmp*)but)->Cols[1] = icocol; ((JBmp*)but)->Cols[2] = icocol; ((JBmp*)but)->Cols[3] = icocol; */ JWReDraw(but); break; } replyMsg(rcvid,0); } }
Threadable::Threadable() { owner = newThread(this); }
static int playFile(const char * file) { int status = -1; media_desc_t mdesc; //DBGLOG("playing file: [%s]", file); memset(&mdesc, 0, sizeof(media_desc_t)); mdesc.ftype = NMS_WP_INVALID; if (!InputIsOurFile(file)) return -1; status = InputInit(file, &mdesc); switch (status) { case 0: //everything is fine break; case 1: WPRINT("InputInit: DM320 is locked by something else. Please try again later."); LOCK_PLAYMUTEX(); errorStatus = NMS_STATUS_OUTPUT_LOCKED; UNLOCK_PLAYMUTEX(); goto bail_clean_input; default: WPRINT("InputInit: Unable to init device!"); LOCK_PLAYMUTEX(); errorStatus = NMS_STATUS_NOT_PLAYABLE; UNLOCK_PLAYMUTEX(); goto bail_clean_input; } LOCK_PLAYMUTEX(); InputGetInfo(file, &info); UNLOCK_PLAYMUTEX(); if (InputStart(file)) { status = -1; goto bail_clean_input; } status = OutputInit(&mdesc,OutputGetMode(),curProportions); switch (status) { case 0: //everything is fine break; case 1: WPRINT("OutputInit: DM320 is locked by something else. Please try again later."); LOCK_PLAYMUTEX(); errorStatus = NMS_STATUS_OUTPUT_LOCKED; UNLOCK_PLAYMUTEX(); goto bail_clean_input; default: WPRINT("OutputInit: Unable to init output !"); LOCK_PLAYMUTEX(); if ((playtype == NPT_FILE) || (totalFiles <= 1) || (repeat == 1)) errorStatus = NMS_STATUS_NOT_PLAYABLE; UNLOCK_PLAYMUTEX(); goto bail_clean_input; } OutputActivateMode(0); LOCK_PLAYMUTEX(); playtime = 0; ffrwLevel = 0; sfrwLevel = 0; sfrwLevelFinal = 0; muted = 0; playing = 1; trackChange = TC_DISABLE; UNLOCK_PLAYMUTEX(); if (newThread(&avThread, NULL, avLoop, NULL)) { status = -1; goto bail_clean_input; } return 0; bail_clean_input: LOCK_PLAYMUTEX(); InputFinish(); UNLOCK_PLAYMUTEX(); return status; }
/* * StartProg - start sampling a program */ void StartProg( char *cmd, char *prog, char *full_args, char *dos_args ) { DWORD code; DWORD tid; CONTEXT con; BOOL waiting_for_first_bp; SIZE_T len; DWORD continue_how; BOOL rc; seg_offset where; DWORD ttid; HANDLE tth; cmd = cmd; strcpy( utilBuff, prog ); strcat( utilBuff, " " ); strcat( utilBuff, full_args ); loadProg( prog, utilBuff ); tid = debugEvent.dwThreadId; tth = CreateThread( NULL, 1024, TimerThread, NULL, 0, &ttid ); if( !tth ) { internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] ); } /* attempt to ensure that we can get all of our samples in one shot */ SetThreadPriority( tth, THREAD_PRIORITY_TIME_CRITICAL ); Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] ); Output( prog ); Output( "\r\n" ); waiting_for_first_bp = TRUE; continue_how = DBG_CONTINUE; for( ;; ) { ContinueDebugEvent( taskPid, tid, continue_how ); rc = WaitForDebugEvent( &debugEvent, INFINITE ); continue_how = DBG_CONTINUE; tid = debugEvent.dwThreadId; switch( debugEvent.dwDebugEventCode ) { case EXCEPTION_DEBUG_EVENT: code = debugEvent.u.Exception.ExceptionRecord.ExceptionCode; switch( code ) { case STATUS_SINGLE_STEP: if( timeOut ) { myGetThreadContext( tid, &con ); RecordSample( con.Eip, con.SegCs, tid ); timeOut = FALSE; } break; case STATUS_BREAKPOINT: if( !waiting_for_first_bp ) { myGetThreadContext( tid, &con ); con.Eip--; if( (con.Edx & 0xffff) != 0 ) { /* this is a mark */ ReadProcessMemory( processHandle, (LPVOID)con.Eax, utilBuff, BUFF_SIZE - 1, len ); utilBuff[len] = '\0'; where.segment = con.SegCs; where.offset = con.Eip; WriteMark( utilBuff, where ); } else { /* this passes CommonAddr */ commonAddr.segment = con.Ecx & 0xffff; commonAddr.offset = con.Ebx; } } else { waiting_for_first_bp = FALSE; } break; case STATUS_DATATYPE_MISALIGNMENT: case STATUS_ACCESS_VIOLATION: case STATUS_IN_PAGE_ERROR: case STATUS_NO_MEMORY: case STATUS_ILLEGAL_INSTRUCTION: case STATUS_NONCONTINUABLE_EXCEPTION: case STATUS_INVALID_DISPOSITION: case STATUS_ARRAY_BOUNDS_EXCEEDED: case STATUS_FLOAT_DENORMAL_OPERAND: case STATUS_FLOAT_DIVIDE_BY_ZERO: case STATUS_FLOAT_INVALID_OPERATION: case STATUS_FLOAT_OVERFLOW: case STATUS_FLOAT_STACK_CHECK: case STATUS_FLOAT_UNDERFLOW: case STATUS_INTEGER_DIVIDE_BY_ZERO: case STATUS_INTEGER_OVERFLOW: case STATUS_PRIVILEGED_INSTRUCTION: case STATUS_STACK_OVERFLOW: case STATUS_CONTROL_C_EXIT: if( debugEvent.u.Exception.dwFirstChance ) { continue_how = DBG_EXCEPTION_NOT_HANDLED; } else { Output( MsgArray[MSG_SAMPLE_4 - ERR_FIRST_MESSAGE] ); Output( "\r\n" ); doneSample = TRUE; TerminateProcess( processHandle, 0 ); report(); return; } break; default: continue_how = DBG_EXCEPTION_NOT_HANDLED; break; } break; case LOAD_DLL_DEBUG_EVENT: if( GetDllName( &debugEvent.u.LoadDll, utilBuff, sizeof( utilBuff ) ) ) { codeLoad( debugEvent.u.LoadDll.hFile, (DWORD) debugEvent.u.LoadDll.lpBaseOfDll, utilBuff, SAMP_CODE_LOAD ); } break; case CREATE_THREAD_DEBUG_EVENT: newThread( debugEvent.dwThreadId, debugEvent.u.CreateThread.hThread ); break; case EXIT_THREAD_DEBUG_EVENT: deadThread( debugEvent.dwThreadId ); break; case EXIT_PROCESS_DEBUG_EVENT: doneSample = TRUE; // TerminateProcess( processHandle, 0 ); - already gone!! report(); return; } } } /* StartProg */