EstOutput Unweighted::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos, CountTable* ct) { try { int process = 1; vector<int> processIDS; bool recalc = false; EstOutput results; #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix) //loop through and create all the processes you want while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later process++; }else if (pid == 0){ EstOutput myresults; myresults = driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, ct); if (m->control_pressed) { exit(0); } //pass numSeqs to parent ofstream out; string tempFile = outputDir + m->mothurGetpid(process) + ".unweighted.results.temp"; m->openOutputFile(tempFile, out); out << myresults.size() << endl; for (int i = 0; i < myresults.size(); i++) { out << myresults[i] << '\t'; } out << endl; out.close(); exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(process) + "\n"); processors = process; for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } //wait to die for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } m->control_pressed = false; for (int i=0;i<processIDS.size();i++) { m->mothurRemove(outputDir + (toString(processIDS[i]) + ".unweighted.results.temp")); } recalc = true; break; } } if (recalc) { //test line, also set recalc to true. //for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } m->control_pressed = false; for (int i=0;i<processIDS.size();i++) {m->mothurRemove(outputDir + (toString(processIDS[i]) + ".unweighted.results.temp"));}processors=3; m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(processors) + "\n"); //if the users enters no groups then give them the score of all groups int numGroups = m->getNumGroups(); //calculate number of comparsions int numComp = 0; vector< vector<string> > namesOfGroupCombos; for (int r=0; r<numGroups; r++) { for (int l = 0; l < r; l++) { numComp++; vector<string> groups; groups.push_back((m->getGroups())[r]); groups.push_back((m->getGroups())[l]); namesOfGroupCombos.push_back(groups); } } if (numComp != 1) { vector<string> groups; if (numGroups == 0) { //get score for all users groups for (int i = 0; i < (ct->getNamesOfGroups()).size(); i++) { if ((ct->getNamesOfGroups())[i] != "xxx") { groups.push_back((ct->getNamesOfGroups())[i]); } } namesOfGroupCombos.push_back(groups); }else { for (int i = 0; i < m->getNumGroups(); i++) { groups.push_back((m->getGroups())[i]); } namesOfGroupCombos.push_back(groups); } } lines.clear(); int remainingPairs = namesOfGroupCombos.size(); int startIndex = 0; for (int remainingProcessors = processors; remainingProcessors > 0; remainingProcessors--) { int numPairs = remainingPairs; //case for last processor if (remainingProcessors != 1) { numPairs = ceil(remainingPairs / remainingProcessors); } lines.push_back(linePair(startIndex, numPairs)); //startIndex, numPairs startIndex = startIndex + numPairs; remainingPairs = remainingPairs - numPairs; } results.clear(); processIDS.resize(0); process = 1; //loop through and create all the processes you want while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later process++; }else if (pid == 0){ EstOutput myresults; myresults = driver(t, namesOfGroupCombos, lines[process].start, lines[process].num, ct); if (m->control_pressed) { exit(0); } //pass numSeqs to parent ofstream out; string tempFile = outputDir + m->mothurGetpid(process) + ".unweighted.results.temp"; m->openOutputFile(tempFile, out); out << myresults.size() << endl; for (int i = 0; i < myresults.size(); i++) { out << myresults[i] << '\t'; } out << endl; out.close(); exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } exit(0); } } } results = driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, ct); //force parent to wait until all the processes are done for (int i=0;i<(processors-1);i++) { int temp = processIDS[i]; wait(&temp); } if (m->control_pressed) { return results; } //get data created by processes for (int i=0;i<(processors-1);i++) { ifstream in; string s = outputDir + toString(processIDS[i]) + ".unweighted.results.temp"; m->openInputFile(s, in); //get quantiles if (!in.eof()) { int num; in >> num; m->gobble(in); if (m->control_pressed) { break; } double w; for (int j = 0; j < num; j++) { in >> w; results.push_back(w); } m->gobble(in); } in.close(); m->mothurRemove(s); } #else //fill in functions vector<unweightedData*> pDataArray; DWORD dwThreadIdArray[processors-1]; HANDLE hThreadArray[processors-1]; vector<CountTable*> cts; vector<Tree*> trees; //Create processor worker threads. for( int i=1; i<processors; i++ ){ CountTable* copyCount = new CountTable(); copyCount->copy(ct); Tree* copyTree = new Tree(copyCount); copyTree->getCopy(t); cts.push_back(copyCount); trees.push_back(copyTree); unweightedData* tempweighted = new unweightedData(m, lines[i].start, lines[i].num, namesOfGroupCombos, copyTree, copyCount, includeRoot); pDataArray.push_back(tempweighted); processIDS.push_back(i); hThreadArray[i-1] = CreateThread(NULL, 0, MyUnWeightedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]); } results = driver(t, namesOfGroupCombos, lines[0].start, lines[0].num, ct); //Wait until all threads have terminated. WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE); //Close all thread handles and free memory allocations. for(int i=0; i < pDataArray.size(); i++){ for (int j = 0; j < pDataArray[i]->results.size(); j++) { results.push_back(pDataArray[i]->results[j]); } delete cts[i]; delete trees[i]; CloseHandle(hThreadArray[i]); delete pDataArray[i]; } #endif return results; }
bool CWebServer::CallCGI(CWebClientSocket* pClient, CStringA& hdr, CStringA& body, CStringA& mime) { CString path = pClient->m_path, redir = path; if(!ToLocalPath(path, redir)) return false; CString ext = CPath(path).GetExtension().MakeLower(); CPath dir(path); dir.RemoveFileSpec(); CString cgi; if(!m_cgi.Lookup(ext, cgi) || !CPath(cgi).FileExists()) return false; HANDLE hProcess = GetCurrentProcess(); HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup = NULL; HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup = NULL; SECURITY_ATTRIBUTES saAttr; ZeroMemory(&saAttr, sizeof(saAttr)); saAttr.nLength = sizeof(saAttr); saAttr.bInheritHandle = TRUE; if(CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) { BOOL fSuccess = DuplicateHandle(hProcess, hChildStdoutRd, hProcess, &hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hChildStdoutRd); } if(CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) { BOOL fSuccess = DuplicateHandle(hProcess, hChildStdinWr, hProcess, &hChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hChildStdinWr); } STARTUPINFO siStartInfo; ZeroMemory(&siStartInfo, sizeof(siStartInfo)); siStartInfo.cb = sizeof(siStartInfo); siStartInfo.hStdError = hChildStdoutWr; siStartInfo.hStdOutput = hChildStdoutWr; siStartInfo.hStdInput = hChildStdinRd; siStartInfo.dwFlags |= STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; siStartInfo.wShowWindow = SW_HIDE; PROCESS_INFORMATION piProcInfo; ZeroMemory(&piProcInfo, sizeof(piProcInfo)); CStringA envstr; if(LPVOID lpvEnv = GetEnvironmentStrings()) { CString str; CAtlList<CString> env; for(LPTSTR lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable += _tcslen(lpszVariable)+1) if(lpszVariable != (LPTSTR)lpvEnv) env.AddTail(lpszVariable); env.AddTail(_T("GATEWAY_INTERFACE=CGI/1.1")); env.AddTail(_T("SERVER_SOFTWARE=Media Player Classic/6.4.x.y")); env.AddTail(_T("SERVER_PROTOCOL=") + pClient->m_ver); env.AddTail(_T("REQUEST_METHOD=") + pClient->m_cmd); env.AddTail(_T("PATH_INFO=") + redir); env.AddTail(_T("PATH_TRANSLATED=") + path); env.AddTail(_T("SCRIPT_NAME=") + redir); env.AddTail(_T("QUERY_STRING=") + pClient->m_query); if(pClient->m_hdrlines.Lookup(_T("content-type"), str)) env.AddTail(_T("CONTENT_TYPE=") + str); if(pClient->m_hdrlines.Lookup(_T("content-length"), str)) env.AddTail(_T("CONTENT_LENGTH=") + str); POSITION pos = pClient->m_hdrlines.GetStartPosition(); while(pos) { CString key = pClient->m_hdrlines.GetKeyAt(pos); CString value = pClient->m_hdrlines.GetNextValue(pos); key.Replace(_T("-"), _T("_")); key.MakeUpper(); env.AddTail(_T("HTTP_") + key + _T("=") + value); } CString name; UINT port; if(pClient->GetPeerName(name, port)) { str.Format(_T("%d"), port); env.AddTail(_T("REMOTE_ADDR=")+name); env.AddTail(_T("REMOTE_HOST=")+name); env.AddTail(_T("REMOTE_PORT=")+str); } if(pClient->GetSockName(name, port)) { str.Format(_T("%d"), port); env.AddTail(_T("SERVER_NAME=")+name); env.AddTail(_T("SERVER_PORT=")+str); } env.AddTail(_T("\0")); str = Implode(env, '\0'); envstr = CStringA(str, str.GetLength()); FreeEnvironmentStrings((LPTSTR)lpvEnv); } TCHAR* cmdln = new TCHAR[32768]; _sntprintf(cmdln, 32768, _T("\"%s\" \"%s\""), cgi, path); if(hChildStdinRd && hChildStdoutWr) if(CreateProcess( NULL, cmdln, NULL, NULL, TRUE, 0, envstr.GetLength() ? (LPVOID)(LPCSTR)envstr : NULL, dir, &siStartInfo, &piProcInfo)) { DWORD ThreadId; CreateThread(NULL, 0, KillCGI, (LPVOID)piProcInfo.hProcess, 0, &ThreadId); static const int BUFFSIZE = 1024; DWORD dwRead, dwWritten = 0; int i = 0, len = pClient->m_data.GetLength(); for(; i < len; i += dwWritten) if(!WriteFile(hChildStdinWrDup, (LPCSTR)pClient->m_data + i, min(len - i, BUFFSIZE), &dwWritten, NULL)) break; CloseHandle(hChildStdinWrDup); CloseHandle(hChildStdoutWr); body.Empty(); CStringA buff; while(i == len && ReadFile(hChildStdoutRdDup, buff.GetBuffer(BUFFSIZE), BUFFSIZE, &dwRead, NULL) && dwRead) { buff.ReleaseBufferSetLength(dwRead); body += buff; } int hdrend = body.Find("\r\n\r\n"); if(hdrend >= 0) { hdr = body.Left(hdrend+2); body = body.Mid(hdrend+4); } CloseHandle(hChildStdinRd); CloseHandle(hChildStdoutRdDup); CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); } else { body = _T("CGI Error"); } delete [] cmdln; return true; }
int main(int argc, char **argv){ if( argc<2){ printf("Usage: %s <ip address>\n", argv[0]); return 1; } if( IsDebuggerPresent()){ HANDLE iphlpapi=LoadLibrary("iphlpapi.dll"); if( !iphlpapi){ perror("iphlpapi.dll"); return 1; } FARPROC IcmpSendEcho=GetProcAddress(iphlpapi, "IcmpSendEcho"); FARPROC IcmpCreateFile=GetProcAddress(iphlpapi, "IcmpCreateFile"); FARPROC IcmpCloseHandle=GetProcAddress(iphlpapi, "IcmpCloseHandle"); if( (IcmpSendEcho && IcmpCreateFile && IcmpCloseHandle)==0){ perror("icmp functions"); return 1; } unsigned long ipaddr=INADDR_NONE, params[2]; HANDLE hIcmpFile; char data[32], *reply; int replySize=sizeof(ICMP_ECHO_REPLY)+sizeof(data); if( (ipaddr=inet_addr(argv[1]))==INADDR_NONE){ perror("Illegal IP address!"); return 1; } if( (hIcmpFile=(HANDLE)IcmpCreateFile())==INVALID_HANDLE_VALUE){ perror("IcmpCreateFile"); return 1; } reply=(char *)malloc(replySize); ZeroMemory(data, sizeof(data)); params[0]=PARAM; params[1]=(unsigned long)GetProcAddress(iphlpapi, "IcmpSendEcho2Ex"); RaiseException(EXCEPTION_BREAKPOINT, 0, 2, params); puts("Exception raised!"); IcmpSendEcho(hIcmpFile, ipaddr, data, sizeof(data), NULL, reply, replySize, 1000); puts("This line should never be shown..."); IcmpCloseHandle(hIcmpFile); return 0; } PROCESS_INFORMATION pi; STARTUPINFO si; HANDLE hProcess, hThread; DEBUG_EVENT debugEvent; EXCEPTION_RECORD *ExceptionRecord=&debugEvent.u.Exception.ExceptionRecord; CONTEXT context; FARPROC IcmpSendEcho2Ex=NULL; char path[256], args[512], originalByte[1]; ZeroMemory(π, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); ZeroMemory(&debugEvent, sizeof(DEBUG_EVENT)); ZeroMemory(&context, sizeof(CONTEXT)); ZeroMemory(path, sizeof(path)); ZeroMemory(args, sizeof(args)); si.cb=sizeof(STARTUPINFO); si.dwFlags=STARTF_USESHOWWINDOW; si.wShowWindow=SW_HIDE; context.ContextFlags=CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS; GetModuleFileName(NULL, path, sizeof(path)-1); snprintf(args, sizeof(args)-1, "%s %s", path, argv[1]); if( !CreateProcess( NULL, args, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, π )){ perror("CreateProcess"); return 1; } if( (hProcess=OpenProcess(PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId))==NULL){ perror("OpenProcess"); return 1; } HANDLE kernel32=LoadLibrary("kernel32.dll"); FARPROC DebugSetProcessKillOnExit=GetProcAddress(kernel32, "DebugSetProcessKillOnExit"); FARPROC DebugActiveProcessStop=GetProcAddress(kernel32, "DebugActiveProcessStop"); FARPROC OpenThread=GetProcAddress(kernel32, "OpenThread"); CloseHandle(kernel32); DebugSetProcessKillOnExit(TRUE); while(WaitForDebugEvent(&debugEvent, INFINITE) && debugEvent.dwDebugEventCode!=EXIT_PROCESS_DEBUG_EVENT){ if( debugEvent.dwDebugEventCode==EXCEPTION_DEBUG_EVENT && ExceptionRecord->ExceptionCode==EXCEPTION_BREAKPOINT){ if( ExceptionRecord->NumberParameters>1 && ExceptionRecord->ExceptionInformation[0]==PARAM){ IcmpSendEcho2Ex=(FARPROC)ExceptionRecord->ExceptionInformation[1]; printf("IcmpSendEcho2Ex %p\n", IcmpSendEcho2Ex); if( !BreakpointSet(hProcess, IcmpSendEcho2Ex, &originalByte)){ perror("BreakpointSet"); break; } } else if( ExceptionRecord->ExceptionAddress==IcmpSendEcho2Ex){ printf("EIP %p\n", IcmpSendEcho2Ex); if( !BreakpointRetrieve(hProcess, IcmpSendEcho2Ex, &originalByte)){ perror("BreakpointRetrieve"); break; } if((hThread=(HANDLE)OpenThread(THREAD_ALL_ACCESS, FALSE, debugEvent.dwThreadId))==NULL) puts("OpenThread"); if(!GetThreadContext(hThread, &context)) puts("GetThreadContext"); context.Eip -= 1; if(!SetThreadContext(hThread, &context)) puts("SetThreadContext"); CreateThread(NULL, 0, (void *)Terminate, hProcess, 0, NULL); } } else if( debugEvent.dwDebugEventCode==EXCEPTION_DEBUG_EVENT){ puts("Exception!"); DebugActiveProcessStop(debugEvent.dwProcessId); break; } ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, DBG_CONTINUE); ZeroMemory(&debugEvent, sizeof(DEBUG_EVENT)); } return 0; }
bool Thread::start(classID (threadFunction)(classID), classID parameter){ //kill the previous thread this->kill(); //test if the function is true if(threadFunction){ //WINDOWS 32 #ifdef WIN32 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ #elif defined WIN64 //WINDOWS 64 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ #elif defined __linux__ //LINUX pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&threadID, &attr, edkThreadFunc, (void*)this); //test if create the thread if(this->threadID!=(pthread_t)0u){ #elif defined __APPLE__ //APPLE #endif //copy the function this->threadFunc=threadFunction; //copy the parameter this->funcParameter=parameter; //then return true; return true; } } //clean this->cleanThread(); //else he clean the func this->threadFunc=NULL; return false; } bool Thread::start(classID (threadFunction)(classID)){ return this->start(threadFunction,(void*)NULL); } bool Thread::startIn(classID (threadFunction)(classID), classID parameter, edk::uint32 core){ //kill the previous thread this->kill(); //test if the function is true and if the core exist if(threadFunction && core<this->cores){ //WINDOWS 32 #ifdef WIN32 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; SetThreadAffinityMask(this->threadID, mask); #elif defined WIN64 //WINDOWS 64 DWORD flag; this->threadID = CreateThread(NULL, // (DWORD)NULL, // edkThreadFunc, // função da thread (void*)this, // parâmetro da thread (DWORD)NULL, // &flag); //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; SetThreadAffinityMask(this->threadID, mask); #elif defined __linux__ //LINUX pthread_attr_t attr; CPU_SET(core, &this->cpus); //start the attribute pthread_attr_init(&attr); //set the core on the attribute pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &this->cpus); //set affinity pthread_create(&threadID, &attr, edkThreadFunc, (void*)this); //test if create the thread if(this->threadID!=(pthread_t)0u){ #elif defined __APPLE__ //APPLE #endif //copy the function this->threadFunc=threadFunction; //copy the parameter this->funcParameter=parameter; //then return true; return true; } } //clean this->cleanThread(); //else he clean the func this->threadFunc=NULL; return false; } bool Thread::startIn(classID (threadFunction)(classID), edk::uint32 core){ return this->startIn(threadFunction, NULL, core); } //change the threadCore bool Thread::changeCore(edk::uint32 core){ //test if have the core if(core<this->cores){ #ifdef WIN32 //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; if(SetThreadAffinityMask(this->threadID, mask)){ return true; #elif defined WIN64 //WINDOWS 64 //test if create the thread if(this->threadID!=(HANDLE)0u){ DWORD_PTR mask = core; if(SetThreadAffinityMask(this->threadID, mask)){ return true; #elif defined __linux__ //test if have the thread if(this->threadID!=(pthread_t)0u){ CPU_ZERO(&this->cpus); CPU_SET(core, &this->cpus); //set the core if(!pthread_setaffinity_np(this->threadID,sizeof(cpu_set_t), &this->cpus)){ return true; } #elif defined __APPLE__ //APPLE #endif } } return false; } bool Thread::runFunc(){ if(this->threadFunc){ //test if have parameter if(this->funcParameter){ //then he cant run the function this->threadFunc((void*)this->funcParameter); } else{ //then he cant run the function this->threadFunc((void*)NULL); } //clean the function this->threadFunc=NULL; this->funcParameter=NULL; //return true; return true; } //else return false return false; } bool Thread::isAlive(){ //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, 0u) == WAIT_TIMEOUT){ //thread still alive return true return true; } } #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, 0u) == WAIT_TIMEOUT){ //thread still alive return true return true; } } #elif defined __linux__ //WINDOWS 64 if(this->threadID){ //Then wait for the thread if(pthread_kill(this->threadID, 0u)!=3u){ //thread still alive return true return true; } } #elif defined __APPLE__ //APPLE #endif //else return false; return false; } bool Thread::waitEnd(uint64 milliseconds){ //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, milliseconds) == WAIT_TIMEOUT){ //thread still alive then return true; } } #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Then wait for the thread if(WaitForSingleObject(threadID, milliseconds) == WAIT_TIMEOUT){ //thread still alive then return true; } } #elif defined __linux__//Linux //first he sleep usleep(milliseconds*1000); //test if thread still alive if(this->isAlive()){ // return true; } #elif __APPLE__ //APPLE #endif //clean this->cleanThread(); //else return false; return false; } bool Thread::waitEnd(){ bool ret=false; //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Then wait for the thread WaitForSingleObject(threadID, INFINITE); //then return true ret = true; } #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Then wait for the thread WaitForSingleObject(threadID, INFINITE); //then return true ret = true; } #elif defined __linux__ //LINUX if(this->threadID){ //then wait the end of the thread pthread_join(this->threadID,NULL); //then return true ret = true; } #elif defined __APPLE__ //APPLE #endif //clean this->cleanThread(); //return true or false return ret; } bool Thread::kill(){ bool ret = false; //WINDOWS 32 #ifdef WIN32 if(this->threadID){ //Finish the thread TerminateThread(this->threadID ,(DWORD)NULL ); ret=true; } //clean ID this->threadID=(HANDLE)0u; #elif defined WIN64 //WINDOWS 64 if(this->threadID){ //Finish the thread TerminateThread(this->threadID ,(DWORD)NULL ); ret=true; } #elif defined __linux__ //LINUX if(this->threadID){ //Cancel the thread pthread_cancel(this->threadID); //pthread_attr_destroy(&attr); //Finish the thread ret=true; } #endif //clean this->cleanThread(); //return true or false return ret; } void Thread::killThisThread(){ //WINDOWS 32 #ifdef WIN32 //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); #elif defined WIN64 //WINDOWS 64 //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); #elif defined __linux__ //LINUX //Exit the process pthread_exit(NULL); #elif defined __linux__ //APPLE //Exit the process pthread_exit(NULL); #endif } void Thread::killAllThreads(){ //WINDOWS 32 #ifdef WIN32 /* //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); */ #elif defined WIN64 //WINDOWS 64 /* //Finish the thread TerminateThread(NULL ,(DWORD)NULL ); */ #elif defined __linux__ //LINUX //Exit the process pthread_cancel((pthread_t)NULL); #elif defined __linux__ //APPLE //Exit the process pthread_cancel((pthread_t)NULL); #endif } #if __x86_64__ || __ppc64__ //get the thread id edk::uint64 Thread::getThisThreadID(){ #if WIN64 return GetCurrentThreadId(); #elif __linux__ return pthread_self(); #endif } #else //get the thread id edk::uint32 Thread::getThisThreadID(){ #if WIN32 return GetCurrentThreadId(); #elif __linux__ return pthread_self(); #endif } #endif //return the thread core edk::uint32 Thread::getThisThreadCore(){ #if defined(WIN32) || defined(WIN64) return 0; #elif __linux__ return sched_getcpu(); #endif } edk::uint32 Thread::numberOfCores(){ return edk::multi::Thread::cores; } }
long __stdcall DlgProc ( HWND hWnd , unsigned msg , unsigned wParam , long lParam ) { switch(msg) { case WM_INITDIALOG: //hEdit = GetDlgItem( hWnd , I_EDIT ); //GetClientRect( hEdit , &rect ); hWndCap = capCreateCaptureWindow ( NULL, WS_CHILD | WS_VISIBLE , 0, 0, 320, 240, hWnd, 1235 ); //hWndCap = capCreateCaptureWindow ( NULL, WS_CHILD | WS_VISIBLE , 0, 0, (rect.right-rect.left ), (rect.bottom-rect.top), hEdit, 1235); // вручную заполняем структуру CapVar ZeroMemory( &CapVar, sizeof(COMPVARS) ); CapVar.cbSize = sizeof(COMPVARS); CapVar.dwFlags = ICMF_COMPVARS_VALID; CapVar.cbState = 0; CapVar.fccHandler = mmioFOURCC( 'x', '2', '6', '4' ); CapVar.fccType = ICTYPE_VIDEO; // открываем декомпрессор (долго) CapVar.hic = ICOpen( ICTYPE_VIDEO, CapVar.fccHandler, ICMODE_COMPRESS ); hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)SendThread, NULL, 0, 0 ); return -1 ; case WM_COMMAND: switch(LOWORD(wParam)) { case I_BUTTON_CONN : if( !capDriverConnect( hWndCap, 0 ) ) { EndDialog ( hWnd, 0 ); return -1; } capCaptureGetSetup( hWndCap, &CapParms, sizeof(CAPTUREPARMS) ); CapParms.dwRequestMicroSecPerFrame = 66000; CapParms.fLimitEnabled = FALSE; CapParms.fCaptureAudio = FALSE; CapParms.fMCIControl = FALSE; CapParms.fYield = TRUE; CapParms.vKeyAbort = VK_ESCAPE; CapParms.fAbortLeftMouse = FALSE; CapParms.fAbortRightMouse = FALSE; capCaptureSetSetup( hWndCap, &CapParms, sizeof(CAPTUREPARMS) ); capPreviewScale( hWndCap, 1 ); capPreviewRate( hWndCap, 66 ); capPreviewScale( hWndCap, FALSE ); capPreview( hWndCap, 1 ); //added by jimmy // OPTIONAL STEP: Setup resolution capGetVideoFormat( hWndCap, &InputBmpInfo ,sizeof(InputBmpInfo) ); //InputBmpInfo.bmiHeader.biWidth = 320; //(rect.right-rect.left ); //InputBmpInfo.bmiHeader.biHeight = 240; //(rect.bottom-rect.top); //InputBmpInfo.bmiHeader.biBitCount = 24; capSetVideoFormat( hWndCap, &InputBmpInfo, sizeof(InputBmpInfo) ); //capDriverDisconnect (hWndCap, 0);//Can we do better? //capDriverConnect (hWndCap, 0); capSetCallbackOnFrame( hWndCap, FrameCallBack ); if(CapVar.hic > 0 ) { OutFormatSize = ICCompressGetFormatSize( CapVar.hic, &InputBmpInfo.bmiHeader ); // BITMAPINFO возвращает размер структуры исходных данных InputBmpInfo ICCompressGetFormat( CapVar.hic, &InputBmpInfo.bmiHeader, &OutputBmpInfo.bmiHeader ); // заполняет структуру получаемых данных OutputBmpInfo OutBufferSize = ICCompressGetSize( CapVar.hic, &InputBmpInfo.bmiHeader, &OutputBmpInfo.bmiHeader ); // максимальный размер одного сжатого кадра (полученного) ICSeqCompressFrameStart( &CapVar, &InputBmpInfo ); // начало сжатия } break; case I_BUTTON_EXIT : ICSeqCompressFrameEnd(&CapVar); // конец сжатия ICCompressorFree(&CapVar); ICClose(CapVar.hic); capPreview( hWndCap , false ); capDriverDisconnect( hWndCap ); EndDialog ( hWnd , 0 ) ; break; } return -1 ; case WM_CLOSE : ICSeqCompressFrameEnd(&CapVar); // конец сжатия ICCompressorFree(&CapVar); ICClose(CapVar.hic); capPreview( hWndCap , false ); capDriverDisconnect( hWndCap ); EndDialog ( hWnd , 0 ) ; return -1 ; } return 0 ; }
int CSound::LoadInternal(const char* szFileName, DSBUFFERDESC* pDsbdesc, void* pData, unsigned long dwDataSize){ CSoundLoader* pLoader; char errmsg[512]; if(CS_E_OK!=this->GetLoaderInterface(&pLoader, szFileName, pData, dwDataSize)){ wsprintf(errmsg, "Sound::%sの読み取りインターフェイス取得に失敗.\nファイルが存在するかもしくは対応形式か確認して下さい.", szFileName); ::MessageBox(NULL, errmsg, "", MB_ICONEXCLAMATION|MB_OK|MB_TOPMOST); //FatalAppExit(0, errmsg); return CS_E_NOTFOUND; } if(CSL_E_OK != pLoader->QueryLoadFile(szFileName, pData, dwDataSize)){ wsprintf(errmsg, "Sound::%sの読み取りに失敗.", szFileName); ::MessageBox(NULL, errmsg, "", MB_ICONEXCLAMATION|MB_OK|MB_TOPMOST); //FatalAppExit(0, errmsg); return CS_E_UNEXP; } //初期化 this->AddRef(); this->UnInitialize(); m_Loader = pLoader; if(!m_pPrimaryBuffer){ //プライマリバッファを取得する if(CS_E_OK!=GetPrimaryBuffer(&m_pPrimaryBuffer, DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN | DSBCAPS_PRIMARYBUFFER)) return CS_E_NULL_PRIMARY; } DSBUFFERDESC dsbdesc; zeroMem(&dsbdesc, sizeof(DSBUFFERDESC)); dsbdesc.dwSize = sizeof(DSBUFFERDESC); //全体の長さとWFXの取得 DWORD dwDataLength = m_Loader->GetDecodedLength(); m_Loader->GetWaveFormatEx(&m_wfx); if(dwDataLength >= CS_LIMITLOADONMEMORY){//展開したときのサイズが1MB以上だったらストリーミング再生] //スレッド処理 this->CloseStreamThread(); m_hThreadMessageDispatchEvent = CreateEvent(NULL, FALSE, FALSE, NULL); m_hThread = CreateThread(NULL, 0, this->StreamThread, (void*)this, CREATE_SUSPENDED, &m_dwThreadId); //スレッド生成 // スレッド優先を変更 SetThreadPriority( m_hThread, THREAD_PRIORITY_NORMAL ); // スレッド開始 ResumeThread( m_hThread ); WaitForSingleObject(m_hThreadMessageDispatchEvent, INFINITE);// スレッドメッセージキューが作成されるのを待つ m_isStreamFile = TRUE; //セカンダリバッファ { SAFE_RELEASE(m_pSecondaryBuffer); dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_CTRLPOSITIONNOTIFY| DSBCAPS_GLOBALFOCUS|DSBCAPS_CTRLPAN|DSBCAPS_CTRLVOLUME| DSBCAPS_CTRLFREQUENCY|DSBCAPS_LOCSOFTWARE; if(pDsbdesc){ dsbdesc.dwFlags = pDsbdesc->dwFlags; dsbdesc.guid3DAlgorithm = dsbdesc.guid3DAlgorithm; } dsbdesc.lpwfxFormat = &m_wfx; DWORD dwSize = m_wfx.nAvgBytesPerSec * m_dwBufferLengthSec / m_dwNotificationNum; dwSize -= dwSize % m_wfx.nBlockAlign; dsbdesc.dwBufferBytes = dwSize * m_dwNotificationNum; if(!CreateBuffer(&m_pSecondaryBuffer, &dsbdesc, NULL)) return CS_E_NOCANDO; m_dwOneSplittedBufferSize = dwSize;//区切られたバッファの1つのサイズ(バッファ全体はこれ*m_dwNotificationNum } //通知インターフェイス #if !ENABLE_SOUND_POLLING { SAFE_RELEASE(m_pSoundNotify); if(FAILED(m_pSecondaryBuffer->QueryInterface(IID_IDirectSoundNotify, (void**)&m_pSoundNotify))){ return CS_E_NOCANDO; } SAFE_GLOBALFREE(m_pDsbnotify); if(!(m_pDsbnotify = (DSBPOSITIONNOTIFY*)GlobalAlloc(GPTR, m_dwNotificationNum * sizeof(DSBPOSITIONNOTIFY)))){ return CS_E_UNEXP; } m_pNotifyHandle = CreateEvent(NULL, FALSE, FALSE, NULL); //通知ハンドルの作成 for(DWORD i=0; i<m_dwNotificationNum; i++){ //OutputDebugStringFormatted("[%2lu]:%lu\n", i, (m_dwOneSplittedBufferSize*i) + 1); m_pDsbnotify[i].dwOffset = (m_dwOneSplittedBufferSize*i) + 1;// バッファを分割する。通知ポイントは、バッファの区切れ目から1バイト先。こうすることで、スペックの低いマシンでも249ms以内に次のバッファ区間を埋めればよいことになる。 m_pDsbnotify[i].hEventNotify = m_pNotifyHandle; } if(FAILED(m_pSoundNotify->SetNotificationPositions(m_dwNotificationNum, m_pDsbnotify))){ SAFE_GLOBALFREE(m_pDsbnotify); SAFE_RELEASE(m_pSoundNotify); SAFE_CLOSEHANDLE(m_pNotifyHandle); return CS_E_NOCANDO; } } #endif }else{ m_isStreamFile = FALSE; void* pdata = NULL; if(CSL_E_OK != m_Loader->GetDecodedData(&pdata, 0, 0, FALSE)){ } dsbdesc.dwFlags = DSBCAPS_CTRLPAN|DSBCAPS_CTRLVOLUME| DSBCAPS_CTRLFREQUENCY| DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_CTRLPOSITIONNOTIFY| DSBCAPS_GLOBALFOCUS; if(pDsbdesc){ dsbdesc.dwFlags = pDsbdesc->dwFlags; dsbdesc.guid3DAlgorithm = dsbdesc.guid3DAlgorithm; } dsbdesc.dwBufferBytes = dwDataLength; dsbdesc.lpwfxFormat = &m_wfx; SAFE_RELEASE(m_pSecondaryBuffer); if(!CreateBuffer(&m_pSecondaryBuffer, &dsbdesc, NULL)) return CS_E_NOCANDO; //セカンダリバッファの作成 if(!WriteDataToBuffer(&m_pSecondaryBuffer, pdata, 0, dwDataLength)) return CS_E_NOCANDO; //データをバッファに書き込む SAFE_GLOBALFREE(pdata); } SAFE_RELEASE(m_pPrimaryBuffer); return CS_E_OK; }
int _tmain(int argc, _TCHAR* argv[]) { // Init critical section; InitializeCriticalSection(&g_write_queue_cs); // g_write_queue_has_more_data_event = CreateEvent(NULL, FALSE, FALSE, NULL); // g_write_queue_accepts_more_data_event = CreateEvent(NULL, FALSE, TRUE, NULL); for (int i = 0; i<10000; ++i) { char a[5]; sprintf_s(a,"%04d", i); // fitting 4 character string to uint32_t. g_x[i] = *((uint32_t*)a); } g_x[10000] = *((uint32_t*)"9999"); g_hFile = ::CreateFile(L"output.txt", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL); if (g_hFile == INVALID_HANDLE_VALUE) { printf("Oppps"); exit(-1); } // Launch a writer thread. // HANDLE hWriteThread = CreateThread(NULL, 0, &WriteThreadProc, hFile,0, 0); HANDLE hRandomThread1 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread2 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread3 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread4 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread5 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread6 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread7 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); //HANDLE hRandomThread8 = CreateThread(NULL, 0, &RandomThreadProc, 0, 0, 0); g_begin_ticks = GetTickCount64(); ::Sleep(20000); // Let the writing thread know we are done. EnterCriticalSection(&g_write_queue_cs); g_done = true; LeaveCriticalSection(&g_write_queue_cs); //SetEvent(g_write_queue_has_more_data_event); // Wait for writing thread to finish. WaitForSingleObject(hRandomThread1, INFINITE); //WaitForSingleObject(hRandomThread2, INFINITE); //WaitForSingleObject(hRandomThread3, INFINITE); //WaitForSingleObject(hRandomThread4, INFINITE); //WaitForSingleObject(hRandomThread5, INFINITE); //WaitForSingleObject(hRandomThread6, INFINITE); //WaitForSingleObject(hRandomThread7, INFINITE); //WaitForSingleObject(hRandomThread8, INFINITE); // WaitForSingleObject(hWriteThread, INFINITE); g_end_ticks = GetTickCount64(); ::CloseHandle(g_hFile); __int64 delta = g_end_ticks - g_begin_ticks; printf("Speed %.3f MB per sec\n", (g_total_bytes_written * 1000.0) / (1024.0 * 1024 * delta)); char c; scanf("%c", &c); return 0; }
//int main(int argc, char* argv[]) // rTANDEM // .Call("tandem",RTsexp['param'], RTsexp['peptide'], RTsexp['saps'], RTsexp['mods'], RTsexp['spectrum']) SEXP tandem(SEXP param, SEXP peptide, SEXP saps, SEXP mods, SEXP spectrum) // rTANDEM { // rTANDEM // To make sure the SEXP are ok // Rcpp::CharacterVector v_param(param); // rTANDEM // Rcpp::CharacterVector v_peptide(peptide); // rTANDEM // Rcpp::CharacterVector v_saps(saps); // rTANDEM // Rcpp::CharacterVector v_mods(mods); // rTANDEM // Rcpp::CharacterVector v_spectrum(spectrum); // rTANDEM // cout << "param: " << endl; // rTANDEM // for (size_t i = 0; i < v_param.size(); i++) { // rTANDEM // string toPrint(v_param[i]); // rTANDEM // cout << toPrint << endl; // rTANDEM // } // rTANDEM // cout << "peptide: " << endl; // rTANDEM // for (size_t i = 0; i < v_peptide.size(); i++) { // rTANDEM // string toPrint(v_peptide[i]); // rTANDEM // cout << toPrint << endl; // rTANDEM // } // rTANDEM // cout << "saps: " << endl; // rTANDEM // for (size_t i = 0; i < v_saps.size(); i++) { // rTANDEM // string toPrint(v_saps[i]); // rTANDEM // cout << toPrint << endl; // rTANDEM // } // rTANDEM // cout << "mods: " << endl; // rTANDEM // for (size_t i = 0; i < v_mods.size(); i++) { // rTANDEM // string toPrint(v_mods[i]); // rTANDEM // cout << toPrint << endl; // rTANDEM // } // rTANDEM // cout << "spectrum: " << endl; // rTANDEM // for (size_t i = 0; i < v_spectrum.size(); i++) { // rTANDEM // string toPrint(v_spectrum[i]); // rTANDEM // cout << toPrint << endl; // rTANDEM // } // rTANDEM /* * Check the argv array for at least one parameter. * mprocess checks the validity of the file. */ // rTANDEM : since we don't use argc and argv, usage was disabled // if(argc < 2 || argc > 1 && strstr(argv[1],"-L") == argv[1] || argc > 1 && strstr(argv[1],"-h") == argv[1]) { // cout << "\n\nUSAGE: tandem filename\n\nwhere filename is any valid path to an XML input file.\n\n+-+-+-+-+-+-+\n"; // cout << "\nX! TANDEM " << VERSION << "\n"; // cout << "\nCopyright (C) 2003-2011 Ronald C Beavis, all rights reserved\n"; // cout << "This software is a component of the GPM project.\n"; // cout << "Use of this software governed by the Artistic license.\n"; // cout << "If you do not have this license, you can get a copy at\n"; // cout << "http://www.perl.com/pub/a/language/misc/Artistic.html\n"; // cout << "\n+-+-+-+-+-+-+\n\npress <Enter> to continue ..."; // char *pValue = new char[128]; // cin.getline(pValue,127); // delete pValue; // return -1; // } // cout << "\nX! TANDEM " << VERSION << "\n\n"; // /* * Create an mprocess object array */ unsigned long lMaxThreads = 16; mprocess **pProcess = new mprocess*[lMaxThreads]; if(pProcess == NULL) { // cout << "An error was detected creating the processing objects.\nPlease contact a GPM administrator.\n"; Rprintf("An error was detected creating the processing objects.\nPlease contact a GPM administrator.\n"); // return -2; // rTANDEM return R_NilValue; // rTANDEM } #ifdef MSVC DWORD *pId = new DWORD[lMaxThreads]; HANDLE *pHandle = new HANDLE[lMaxThreads]; #else int *pId = new int[lMaxThreads]; int *pHandle = new int[lMaxThreads]; pthread_t pThreads[lMaxThreads]; #endif unsigned long a = 0; while(a < lMaxThreads) { pProcess[a] = NULL; // rTANDEM : There was a warning here during package installation. // pHandle[a] = NULL; // rTANDEM // pId[a] = NULL; // rTANDEM pHandle[a] = 0; // rTANDEM pId[a] = 0; // rTANDEM a++; } pProcess[0] = new mprocess; // cout << "Loading spectra"; Rprintf("Loading spectra\n"); //cout.flush(); /* * Initialize the first mprocess object with the input file name. */ char *pS = new char[1024]; // rTANDEM: We need to change the code so data is no longer loader from file // strcpy(pS,argv[1]); // rTANDEM // if(!pProcess[0]->load(pS)) { if(!pProcess[0]->load(param, peptide, saps, mods, spectrum)); // cout << "\n\nAn error was detected while loading the input parameters.\nPlease follow the advice above or contact a GPM administrator to help you."; // rTANDEM // delete pProcess[0]; // rTANDEM // delete pProcess; // rTANDEM // return -4; // rTANDEM // } // rTANDEM // cout << " loaded.\n"; Rprintf(" loaded.\n"); if(pProcess[0]->m_vSpectra.size() == 0) { // cout << "No input spectra met the acceptance criteria.\n"; Rprintf("No input spectra met the acceptance criteria.\n"); //cout.flush(); delete pProcess[0]; delete pProcess; // return 1; // rTANDEM return R_NilValue; // rTANDEM } pProcess[0]->serialize(); // cout << "Spectra matching criteria = " << (unsigned long)pProcess[0]->m_vSpectra.size() << "\n"; Rprintf("Spectra matching criteria = %l\n", (unsigned long)pProcess[0]->m_vSpectra.size()); //cout.flush(); #ifdef PLUGGABLE_SCORING // cout << "Pluggable scoring enabled.\n"; Rprintf("Pluggable scoring enabled.\n"); #endif /* * Start the mprocess object and wait for it to return. */ unsigned long lThread = pProcess[0]->get_thread(); unsigned long lThreads = pProcess[0]->get_threads(); if(lThreads > lMaxThreads) { lThreads = lMaxThreads; } if(pProcess[0]->m_vSpectra.size() < lThreads) { lThreads = (unsigned long)pProcess[0]->m_vSpectra.size(); if(lThreads < 1) { lThreads = 1; } pProcess[0]->set_threads(lThreads); } #ifdef MSVC DWORD dCount = lThreads - 1; #else int dCount = lThreads - 1; #endif long lSpectra = lThreads + (long)pProcess[0]->m_vSpectra.size()/lThreads; bool bSpectra = true; // cout << "Starting threads ."; Rprintf("Starting threads ."); //cout.flush(); if(lThread != 0xFFFFFFFF) { while(dCount > 0) { pProcess[dCount] = new mprocess; pProcess[dCount]->set_thread(dCount); /* * initialize the new mprocess objects with the spectra already loaded into the first mprocess */ pProcess[dCount]->m_vSpectra.reserve(lSpectra); dCount--; } size_t tCount = pProcess[0]->m_vSpectra.size(); sort(pProcess[0]->m_vSpectra.begin(),pProcess[0]->m_vSpectra.end(),lessThanSpec); size_t tProcesses = lThreads; size_t tRing = 0; vector<mspectrum> vZero; vZero.reserve(lSpectra); do { if(tRing == 0) { vZero.push_back(pProcess[0]->m_vSpectra.back()); } else { pProcess[tRing]->m_vSpectra.push_back(pProcess[0]->m_vSpectra.back()); } tRing++; pProcess[0]->m_vSpectra.pop_back(); if(tRing == tProcesses) { tRing = 0; } } while(pProcess[0]->m_vSpectra.size() != 0); pProcess[0]->m_vSpectra.reserve(vZero.size()); do { pProcess[0]->m_vSpectra.push_back(vZero.back()); vZero.pop_back(); } while(vZero.size() != 0); dCount = lThreads - 1; while(dCount > 0) { if(!pProcess[dCount]->load(pS,pProcess[0])) { // cout << "error pProcess->LoadParameters returned error (main)\r\n"; Rprintf("error pProcess->LoadParameters returned error (main)\r\n"); delete pProcess; // return -4; // rTANDEM return R_NilValue; // rTANDEM } dCount--; // cout << "."; Rprintf("."); //cout.flush(); } } delete pS; dCount = 0; #ifdef MSVC pHandle[dCount] = CreateThread(NULL,0,ProcessThread,(void *)pProcess[dCount],0,&pId[dCount]); #else pthread_create(&pThreads[dCount],NULL,ProcessThread,(void*)pProcess[dCount]); #endif dCount++; /* * Initialize more mprocess objects, if lThread is not 0xFFFFFFFF, which signifies default single * threaded operation. */ if(lThread != 0xFFFFFFFF && bSpectra) { while((unsigned long)(dCount) < lThreads) { #ifdef MSVC pHandle[dCount] = CreateThread(NULL,0,ProcessThread,(void *)pProcess[dCount],0,&pId[dCount]); #else pthread_create(&pThreads[dCount],NULL,ProcessThread,(void*)pProcess[dCount]); #endif dCount++; } } // cout << " started.\n"; Rprintf(" started.\n"); //cout.flush(); // cout << "Computing models:\n"; Rprintf("Computing models:\n"); //cout.flush(); /* * wait until all of the mprocess objects return. */ #ifdef MSVC // DWORD wait = WaitForMultipleObjects(dCount,pHandle,true,INFINITE); a = 0; DWORD dwTime = 100000; DWORD wait = WAIT_TIMEOUT; int iTics = 0; while(a < (unsigned long)(dCount)) { wait = WaitForSingleObject(pHandle[a],100); if(a > 0 && wait == WAIT_TIMEOUT) { if(a == 1) { // cout << "waiting for " << a+1; Rprintf("waiting for %i", a+1); } else { // cout << a+1; Rprintf("%i",a+1); } while(wait == WAIT_TIMEOUT) { wait = WaitForSingleObject(pHandle[a],dwTime); if(wait == WAIT_TIMEOUT) { // cout << "."; Rprintf("."); //cout.flush(); iTics++; if(iTics > 50) { // cout << "|\n\t\t"; Rprintf("|\n\t\t"); //cout.flush(); iTics = 0; } } } } else { while(wait == WAIT_TIMEOUT) { wait = WaitForSingleObject(pHandle[a],dwTime); if(wait == WAIT_TIMEOUT) { // cout << ":"; Rprintf(":"); //cout.flush(); } } if(a == 1) { // cout << "waiting for " << a+1; Rprintf("waiting for %i", a+1); } else if(a == 0) { // cout << "\n\t"; Rprintf("\n\t"); //cout.flush(); } else { // cout << a+1; Rprintf("%i", a+1); } } a++; } if(dCount > 1) { // cout << " done.\n\n"; Rprintf(" done.\n\n"); //cout.flush(); } else { // cout << "\n"; Rprintf("\n"); //cout.flush(); } #else //2003-03-01:note - the declaration below was changed from void **vp; void *vp; int x=0; int wait; for(x=0;x<dCount;x++){ //2003-03-01:note - the 2nd parameter in the call to pthread_join() was changed from vp wait = pthread_join(pThreads[x],&vp); } #endif // cout << "\tsequences modelled = "<< (long)(pProcess[0]->get_protein_count()/1000.0 + 0.5) << " ks\n"; Rprintf("\tsequences modelled = %l ks\n", (long)(pProcess[0]->get_protein_count()/1000.0 + 0.5)); //cout.flush(); pProcess[0]->merge_spectra(); a = 1; /* * merge the results into the first object */ while(a < (unsigned long)(dCount)) { pProcess[0]->merge_map(pProcess[a]->m_mapSequences); pProcess[0]->merge_spectra(pProcess[a]->m_vSpectra); a++; } a = 1; pProcess[0]->load_sequences(); while(a < (unsigned long)(dCount)) { pProcess[a]->merge_map(pProcess[0]->m_mapSequences); pProcess[a]->m_vseqBest = pProcess[0]->m_vseqBest; a++; } /* * Report the contents of the mprocess objects into an XML file as described * in the input file. */ // cout << "Model refinement:\n"; Rprintf("Model refinement:\n"); //cout.flush(); dCount = 0; #ifdef MSVC pHandle[dCount] = CreateThread(NULL,0,RefineThread,(void *)pProcess[dCount],0,&pId[dCount]); #else pthread_create(&pThreads[dCount],NULL,RefineThread,(void*)pProcess[dCount]); #endif dCount++; /* * Initialize more mprocess objects, if lThread is not 0xFFFFFFFF, which signifies default single * threaded operation. */ if(lThread != 0xFFFFFFFF) { while((unsigned long)(dCount) < lThreads) { #ifdef MSVC pHandle[dCount] = CreateThread(NULL,0,RefineThread,(void *)pProcess[dCount],0,&pId[dCount]); #else pthread_create(&pThreads[dCount],NULL,RefineThread,(void*)pProcess[dCount]); #endif dCount++; } } /* * wait until all of the mprocess objects return. */ #ifdef MSVC // wait = WaitForMultipleObjects(dCount,pHandle,true,INFINITE); a = 0; iTics = 0; while(a < (unsigned long)(dCount)) { wait = WaitForSingleObject(pHandle[a],10000); if(a > 0 && wait == WAIT_TIMEOUT) { if(a == 1) { // cout << "waiting for " << a+1; Rprintf("waiting for %i", a+1); } else { // cout << a+1; Rprintf("%i", a+1); } //cout.flush(); while(wait == WAIT_TIMEOUT) { wait = WaitForSingleObject(pHandle[a],dwTime); if(wait == WAIT_TIMEOUT) { // cout << "."; Rprintf("."); //cout.flush(); iTics++; if(iTics > 50) { // cout << "|\n\t\t"; Rprintf("|\n\t\t"); //cout.flush(); iTics = 0; } } } } else { while(wait == WAIT_TIMEOUT) { wait = WaitForSingleObject(pHandle[a],dwTime); if(wait == WAIT_TIMEOUT) { // cout << ":"; Rprintf(":"); //cout.flush(); } } if(a == 1) { // cout << "waiting for " << a+1; Rprintf("waiting for %i", a+1); } else if(a == 0) { // cout << "\n\t"; Rprintf("\n\t"); //cout.flush(); } else { // cout << a+1; Rprintf("%i", a+1); } } a++; } if(dCount > 1) { // cout << " done.\n\n"; Rprintf(" done.\n\n"); //cout.flush(); } else { // cout << "\n"; Rprintf("\n"); //cout.flush(); } #else //2003-03-01:note - the declaration below was changed from void **vp; x=0; for(x=0;x<dCount;x++){ //2003-03-01:note - the 2nd parameter in the call to pthread_join() was changed from vp wait = pthread_join(pThreads[x],&vp); } #endif a = 1; /* * merge the results into the first object */ if(dCount > 1) { // cout << "Merging results:\n"; Rprintf("Merging results:\n"); //cout.flush(); } while(a < (unsigned long)(dCount)) { if(a == 1) { // cout << "\tfrom " << a+1; Rprintf("\tfrom %i", a+1); } else { // cout << a+1; Rprintf("%i", a+1); } //cout.flush(); if(!pProcess[0]->add_spectra(pProcess[a]->m_vSpectra)) { // cout << "adding spectra failed.\n"; Rprintf("adding spectra failed.\n"); } pProcess[0]->merge_statistics(pProcess[a]); pProcess[a]->clear(); pProcess[a]->m_mapSequences.clear(); a++; } if(dCount > 1) { // cout << "\n\n"; Rprintf("\n\n"); //cout.flush(); } //cout.flush(); // cout << "Creating report:\n"; Rprintf("Creating report:\n"); //cout.flush(); pProcess[0]->report(); Rcpp::CharacterVector pathName(pProcess[0]->getPathName()); // rTANDEM size_t tValid = pProcess[0]->get_valid(); size_t tUnique = pProcess[0]->get_unique(); double dE = pProcess[0]->get_error_estimate(); unsigned long lE = (unsigned long)(0.5+dE); unsigned long lEe = (unsigned long)(0.5 + sqrt(dE)); if(lEe == 0) { lEe = 1; } if(dE <= 0.0) { dE = 1.0; } // cout << "\nValid models = " << (unsigned long)tValid << "\n"; Rprintf("\nValid models = %l\n", (unsigned long)tValid); if(tUnique > 0) { // cout << "Unique models = " << (unsigned long)tUnique << "\n"; Rprintf("Unique models = %l\n", (unsigned long)tUnique); // cout << "Estimated false positives = " << lE << " ± "; Rprintf("Estimated false positives = %l ± ", lE); // cout << lEe << "\n"; Rprintf("%l\n", lEe); } // lE = pProcess[0]->get_reversed(); long checkGetReversed = pProcess[0]->get_reversed(); if(lE != -1) { lE = (unsigned long)(pProcess[0]->get_reversed()); // cout << "False positive rate (reversed sequences) = " << lE << "\n"; Rprintf("False positive rate (reversed sequences) = %l\n", lE); } // cout << "\n\n"; Rprintf("\n\n"); /* * Delete the mprocess objects and exit */ a = 0; while(a < 16) { if(pProcess[a] != NULL) { #ifdef MSVC CloseHandle(pHandle[a]); #endif delete pProcess[a]; } a++; } delete pProcess; delete pId; delete pHandle; // return 0; // rTANDEM // return R_NilValue; // rTANDEM return pathName; }
int PreClusterCommand::createProcessesGroups(string newFName, string newNName, string newMFile, vector<string> groups) { try { vector<int> processIDS; int process = 1; int num = 0; bool recalc = false; //sanity check if (groups.size() < processors) { processors = groups.size(); } //divide the groups between the processors vector<linePair> lines; int remainingPairs = groups.size(); int startIndex = 0; for (int remainingProcessors = processors; remainingProcessors > 0; remainingProcessors--) { int numPairs = remainingPairs; //case for last processor if (remainingProcessors != 1) { numPairs = ceil(remainingPairs / remainingProcessors); } lines.push_back(linePair(startIndex, (startIndex+numPairs))); //startIndex, endIndex startIndex = startIndex + numPairs; remainingPairs = remainingPairs - numPairs; } #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix) //loop through and create all the processes you want while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later process++; }else if (pid == 0){ outputNames.clear(); num = driverGroups(newFName + m->mothurGetpid(process) + ".temp", newNName + m->mothurGetpid(process) + ".temp", newMFile, lines[process].start, lines[process].end, groups); string tempFile = m->mothurGetpid(process) + ".outputNames.temp"; ofstream outTemp; m->openOutputFile(tempFile, outTemp); outTemp << outputNames.size(); for (int i = 0; i < outputNames.size(); i++) { outTemp << outputNames[i] << endl; } outTemp.close(); exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(process) + "\n"); processors = process; //successful fork()'s for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } recalc = true; break; } } if (recalc) { lines.clear(); num = 0; processIDS.resize(0); process = 1; int remainingPairs = groups.size(); int startIndex = 0; for (int remainingProcessors = processors; remainingProcessors > 0; remainingProcessors--) { int numPairs = remainingPairs; //case for last processor if (remainingProcessors != 1) { numPairs = ceil(remainingPairs / remainingProcessors); } lines.push_back(linePair(startIndex, (startIndex+numPairs))); //startIndex, endIndex startIndex = startIndex + numPairs; remainingPairs = remainingPairs - numPairs; } while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later process++; }else if (pid == 0){ outputNames.clear(); num = driverGroups(newFName + m->mothurGetpid(process) + ".temp", newNName + m->mothurGetpid(process) + ".temp", newMFile, lines[process].start, lines[process].end, groups); string tempFile = m->mothurGetpid(process) + ".outputNames.temp"; ofstream outTemp; m->openOutputFile(tempFile, outTemp); outTemp << outputNames.size(); for (int i = 0; i < outputNames.size(); i++) { outTemp << outputNames[i] << endl; } outTemp.close(); exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } exit(0); } } } //do my part num = driverGroups(newFName, newNName, newMFile, lines[0].start, lines[0].end, groups); //force parent to wait until all the processes are done for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } for (int i = 0; i < processIDS.size(); i++) { string tempFile = toString(processIDS[i]) + ".outputNames.temp"; ifstream intemp; m->openInputFile(tempFile, intemp); int num; intemp >> num; for (int k = 0; k < num; k++) { string name = ""; intemp >> name; m->gobble(intemp); outputNames.push_back(name); outputTypes["map"].push_back(name); } intemp.close(); m->mothurRemove(tempFile); } #else ////////////////////////////////////////////////////////////////////////////////////////////////////// //Windows version shared memory, so be careful when passing variables through the preClusterData struct. //Above fork() will clone, so memory is separate, but that's not the case with windows, ////////////////////////////////////////////////////////////////////////////////////////////////////// vector<preClusterData*> pDataArray; DWORD dwThreadIdArray[processors-1]; HANDLE hThreadArray[processors-1]; //Create processor worker threads. for( int i=1; i<processors; i++ ){ // Allocate memory for thread data. string extension = toString(i) + ".temp"; preClusterData* tempPreCluster = new preClusterData(fastafile, namefile, groupfile, countfile, (newFName+extension), (newNName+extension), newMFile, groups, m, lines[i].start, lines[i].end, diffs, topdown, i); pDataArray.push_back(tempPreCluster); processIDS.push_back(i); //MySeqSumThreadFunction is in header. It must be global or static to work with the threads. //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier hThreadArray[i-1] = CreateThread(NULL, 0, MyPreclusterThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]); } //using the main process as a worker saves time and memory num = driverGroups(newFName, newNName, newMFile, lines[0].start, lines[0].end, groups); //Wait until all threads have terminated. WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE); //Close all thread handles and free memory allocations. for(int i=0; i < pDataArray.size(); i++){ if (pDataArray[i]->count != (pDataArray[i]->end-pDataArray[i]->start)) { m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end-pDataArray[i]->start) + " groups assigned to it, quitting. \n"); m->control_pressed = true; } for (int j = 0; j < pDataArray[i]->mapFileNames.size(); j++) { outputNames.push_back(pDataArray[i]->mapFileNames[j]); outputTypes["map"].push_back(pDataArray[i]->mapFileNames[j]); } CloseHandle(hThreadArray[i]); delete pDataArray[i]; } #endif //append output files for(int i=0;i<processIDS.size();i++){ //newFName = m->getFullPathName(".\\" + newFName); //newNName = m->getFullPathName(".\\" + newNName); m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName); m->mothurRemove((newFName + toString(processIDS[i]) + ".temp")); m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName); m->mothurRemove((newNName + toString(processIDS[i]) + ".temp")); } return num; } catch(exception& e) { m->errorOut(e, "PreClusterCommand", "createProcessesGroups"); exit(1); } }
/* * Program entry point * */ int main(int argc, char **argv) { DWORD lRetVal = 0; ARPPacket lARPPacket; SCANPARAMS lScanParams; unsigned long lIPCounter = 0; unsigned long lStartIP = 0; unsigned long lStopIP = 0; unsigned long lDstIP = 0; HANDLE lThreadHandle = INVALID_HANDLE_VALUE; DWORD lThreadId = 0; int lCounter = 0; pcap_if_t *lAllDevs = NULL; pcap_if_t *lDevice = NULL; char lTemp[PCAP_ERRBUF_SIZE]; HANDLE lICMPFile = INVALID_HANDLE_VALUE; char lSendData[32] = "Data Buffer"; DWORD lReplySize = 0; LPVOID lReplyBuffer = NULL; unsigned long ipaddr = 0; char *lIFCName = argv[1]; HANDLE lARPReplyThreadHandle = INVALID_HANDLE_VALUE; DWORD lARPReplyThreadID = 0; struct sockaddr_in lPeerIP; char lPeerIPStr[MAX_BUF_SIZE + 1]; /* * Initialisation */ ZeroMemory(&lScanParams, sizeof(lScanParams)); InitializeCriticalSectionAndSpinCount(&gWriteLog, 0x00000400); if (argc >= 4) { ZeroMemory(&lARPPacket, sizeof(lARPPacket)); GetIFCDetails(argv[1], &lScanParams); lStartIP = ntohl(inet_addr(argv[2])); lStopIP = ntohl(inet_addr(argv[3])); /* * Start ARP Reply listener thread */ LogMsg("main() : Starting CaptureARPReplies\n"); if ((lARPReplyThreadHandle = CreateThread(NULL, 0, CaptureARPReplies, &lScanParams, 0, &lARPReplyThreadID)) != NULL) { if (lStartIP <= lStopIP) { strncpy(lScanParams.IFCString, argv[1], sizeof(lScanParams.IFCString)-1); /* * Open interface. */ if ((lScanParams.IfcWriteHandle = pcap_open(lIFCName, 65536, PCAP_OPENFLAG_NOCAPTURE_LOCAL|PCAP_OPENFLAG_MAX_RESPONSIVENESS, 5, NULL, lTemp)) != NULL) { for (lIPCounter = lStartIP; lIPCounter <= lStopIP; lIPCounter++) { if (memcmp(lScanParams.LocalIP, &lIPCounter, BIN_IP_LEN) && memcmp(lScanParams.GWIP, &lIPCounter, BIN_IP_LEN)) { /* * Send WhoHas ARP request and sleep ... */ SendARPWhoHas(&lScanParams, lIPCounter); lPeerIP.sin_addr.s_addr = htonl(lIPCounter); strncpy(lPeerIPStr, inet_ntoa(lPeerIP.sin_addr), sizeof(lPeerIPStr)-1); LogMsg("Ping %s", lPeerIPStr); Sleep(SLEEP_BETWEEN_ARPS); } // if (memcmp... } // for (; lStartI... /* * Wait for all ARP replies and terminate thread. */ Sleep(2000); TerminateThread(lARPReplyThreadHandle, 0); CloseHandle(lARPReplyThreadHandle); if (lScanParams.IfcWriteHandle) pcap_close((pcap_t *) lScanParams.IfcWriteHandle); } // if ((lIFCHandle... else LogMsg("main() : pcap_open() failed\n"); } else { LogMsg("main() : Something is wrong with the start and/or end IP!\n"); lRetVal = 1; } // if (lStart... } // if ((lPOISO... } // if (argc >= 4)... DeleteCriticalSection(&gWriteLog); return(lRetVal); }
DWORD WINAPI Link_ThreadProc (LPVOID lpParameter) { BYTE pBuffer[LINK_BUFFER_SIZE] ; DWORD nRequestSize ; BOOL bSuccess ; HANDLE aEvents[2] ; OVERLAPPED ov ; TRACE ; ov.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL) ; // list of events aEvents[0] = ov.hEvent ; aEvents[1] = g_data.hStopEvent ; while(1) { TRACE_INFO (TEXT("Waiting request from driver...\n")) ; bSuccess = DeviceIoControl (g_data.hDriver, IOCTL_LINK_DRV2APP, NULL, 0, pBuffer, LINK_BUFFER_SIZE, &nRequestSize, &ov) ; if( ! bSuccess ) { if( GetLastError()==ERROR_IO_PENDING ) { DWORD nWaitResult = WaitForMultipleObjects (2, aEvents, FALSE, INFINITE) ; if( nWaitResult != WAIT_OBJECT_0 ) { TRACE_INFO (TEXT("Exiting from app-link loop\n")) ; break ; } GetOverlappedResult (g_data.hDriver, &ov, &nRequestSize, FALSE) ; } else { TRACE_ERROR (TEXT("DeviceIoControl failed (0x%08X)\n"), GetLastError()) ; break ; } } if( nRequestSize >= sizeof(REQUEST_HEADER) ) { UINT iSlot ; iSlot = ((REQUEST_HEADER*)pBuffer)->iSlot ; if( iSlot < SLOT_COUNT ) { HANDLE hThread ; TRACE_INFO (TEXT("Slot%u : Request received\n"), iSlot) ; memcpy (g_data.aSlots[iSlot].pBuffer, pBuffer, LINK_BUFFER_SIZE) ; g_data.aSlots[iSlot].nRequestSize = nRequestSize ; hThread = CreateThread (NULL, 0, _Link_RequestThreadProc, (LPVOID)iSlot, 0, NULL) ; CloseHandle (hThread) ; } else { TRACE_ERROR (TEXT("Slot number (%u) is invalid\n"), iSlot) ; } } else { TRACE_ERROR (TEXT("Request size (%u) is invalid\n"), nRequestSize) ; } } TRACE_INFO (TEXT("Cancelling pending IO\n")) ; CancelIo (g_data.hDriver) ; TRACE_INFO (TEXT("Cancel completed\n")) ; CloseHandle (ov.hEvent) ; return 0 ; }
int SummarySharedCommand::process(vector<SharedRAbundVector*> thisLookup, string sumFileName, string sumAllFileName) { try { vector< vector< vector<seqDist> > > calcDistsTotals; //each iter, one for each calc, then each groupCombos dists. this will be used to make .dist files vector< vector<seqDist> > calcDists; calcDists.resize(sumCalculators.size()); for (int thisIter = 0; thisIter < iters+1; thisIter++) { vector<SharedRAbundVector*> thisItersLookup = thisLookup; if (subsample && (thisIter != 0)) { //we want the summary results for the whole dataset, then the subsampling SubSample sample; vector<string> tempLabels; //dont need since we arent printing the sampled sharedRabunds //make copy of lookup so we don't get access violations vector<SharedRAbundVector*> newLookup; for (int k = 0; k < thisItersLookup.size(); k++) { SharedRAbundVector* temp = new SharedRAbundVector(); temp->setLabel(thisItersLookup[k]->getLabel()); temp->setGroup(thisItersLookup[k]->getGroup()); newLookup.push_back(temp); } //for each bin for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) { if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; } for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); } } tempLabels = sample.getSample(newLookup, subsampleSize); thisItersLookup = newLookup; } if(processors == 1){ driver(thisItersLookup, 0, numGroups, sumFileName+".temp", sumAllFileName+".temp", calcDists); m->appendFiles((sumFileName + ".temp"), sumFileName); m->mothurRemove((sumFileName + ".temp")); if (mult) { m->appendFiles((sumAllFileName + ".temp"), sumAllFileName); m->mothurRemove((sumAllFileName + ".temp")); } }else{ int process = 1; vector<int> processIDS; #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix) //loop through and create all the processes you want while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); process++; }else if (pid == 0){ driver(thisItersLookup, lines[process].start, lines[process].end, sumFileName + m->mothurGetpid(process) + ".temp", sumAllFileName + m->mothurGetpid(process) + ".temp", calcDists); //only do this if you want a distance file if (createPhylip) { string tempdistFileName = m->getRootName(m->getSimpleName(sumFileName)) + m->mothurGetpid(process) + ".dist"; ofstream outtemp; m->openOutputFile(tempdistFileName, outtemp); for (int i = 0; i < calcDists.size(); i++) { outtemp << calcDists[i].size() << endl; for (int j = 0; j < calcDists[i].size(); j++) { outtemp << calcDists[i][j].seq1 << '\t' << calcDists[i][j].seq2 << '\t' << calcDists[i][j].dist << endl; } } outtemp.close(); } exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } exit(0); } } //parent do your part driver(thisItersLookup, lines[0].start, lines[0].end, sumFileName + m->mothurGetpid(process) + ".temp", sumAllFileName + m->mothurGetpid(process) + ".temp", calcDists); m->appendFiles((sumFileName + m->mothurGetpid(process) + ".temp"), sumFileName); m->mothurRemove((sumFileName + m->mothurGetpid(process) + ".temp")); if (mult) { m->appendFiles((sumAllFileName + m->mothurGetpid(process) + ".temp"), sumAllFileName); } //force parent to wait until all the processes are done for (int i = 0; i < processIDS.size(); i++) { int temp = processIDS[i]; wait(&temp); } for (int i = 0; i < processIDS.size(); i++) { m->appendFiles((sumFileName + toString(processIDS[i]) + ".temp"), sumFileName); m->mothurRemove((sumFileName + toString(processIDS[i]) + ".temp")); if (mult) { m->mothurRemove((sumAllFileName + toString(processIDS[i]) + ".temp")); } if (createPhylip) { string tempdistFileName = m->getRootName(m->getSimpleName(sumFileName)) + toString(processIDS[i]) + ".dist"; ifstream intemp; m->openInputFile(tempdistFileName, intemp); for (int k = 0; k < calcDists.size(); k++) { int size = 0; intemp >> size; m->gobble(intemp); for (int j = 0; j < size; j++) { int seq1 = 0; int seq2 = 0; float dist = 1.0; intemp >> seq1 >> seq2 >> dist; m->gobble(intemp); seqDist tempDist(seq1, seq2, dist); calcDists[k].push_back(tempDist); } } intemp.close(); m->mothurRemove(tempdistFileName); } } #else ////////////////////////////////////////////////////////////////////////////////////////////////////// //Windows version shared memory, so be careful when passing variables through the summarySharedData struct. //Above fork() will clone, so memory is separate, but that's not the case with windows, //Taking advantage of shared memory to pass results vectors. ////////////////////////////////////////////////////////////////////////////////////////////////////// vector<summarySharedData*> pDataArray; DWORD dwThreadIdArray[processors-1]; HANDLE hThreadArray[processors-1]; //Create processor worker threads. for( int i=1; i<processors; i++ ){ //make copy of lookup so we don't get access violations vector<SharedRAbundVector*> newLookup; for (int k = 0; k < thisLookup.size(); k++) { SharedRAbundVector* temp = new SharedRAbundVector(); temp->setLabel(thisLookup[k]->getLabel()); temp->setGroup(thisLookup[k]->getGroup()); newLookup.push_back(temp); } //for each bin for (int k = 0; k < thisItersLookup[0]->getNumBins(); k++) { if (m->control_pressed) { for (int j = 0; j < newLookup.size(); j++) { delete newLookup[j]; } return 0; } for (int j = 0; j < thisItersLookup.size(); j++) { newLookup[j]->push_back(thisItersLookup[j]->getAbundance(k), thisItersLookup[j]->getGroup()); } } // Allocate memory for thread data. summarySharedData* tempSum = new summarySharedData((sumFileName+toString(i)+".temp"), m, lines[i].start, lines[i].end, Estimators, newLookup); pDataArray.push_back(tempSum); processIDS.push_back(i); hThreadArray[i-1] = CreateThread(NULL, 0, MySummarySharedThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]); } //parent do your part driver(thisItersLookup, lines[0].start, lines[0].end, sumFileName +"0.temp", sumAllFileName + "0.temp", calcDists); m->appendFiles((sumFileName + "0.temp"), sumFileName); m->mothurRemove((sumFileName + "0.temp")); if (mult) { m->appendFiles((sumAllFileName + "0.temp"), sumAllFileName); } //Wait until all threads have terminated. WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE); //Close all thread handles and free memory allocations. for(int i=0; i < pDataArray.size(); i++){ if (pDataArray[i]->count != (pDataArray[i]->end-pDataArray[i]->start)) { m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end-pDataArray[i]->start) + " groups assigned to it, quitting. \n"); m->control_pressed = true; } m->appendFiles((sumFileName + toString(processIDS[i]) + ".temp"), sumFileName); m->mothurRemove((sumFileName + toString(processIDS[i]) + ".temp")); for (int j = 0; j < pDataArray[i]->thisLookup.size(); j++) { delete pDataArray[i]->thisLookup[j]; } if (createPhylip) { for (int k = 0; k < calcDists.size(); k++) { int size = pDataArray[i]->calcDists[k].size(); for (int j = 0; j < size; j++) { calcDists[k].push_back(pDataArray[i]->calcDists[k][j]); } } } CloseHandle(hThreadArray[i]); delete pDataArray[i]; } #endif } if (subsample && (thisIter != 0)) { //we want the summary results for the whole dataset, then the subsampling calcDistsTotals.push_back(calcDists); //clean up memory for (int i = 0; i < thisItersLookup.size(); i++) { delete thisItersLookup[i]; } thisItersLookup.clear(); }else { if (createPhylip) { for (int i = 0; i < calcDists.size(); i++) { if (m->control_pressed) { break; } //initialize matrix vector< vector<double> > matrix; //square matrix to represent the distance matrix.resize(thisLookup.size()); for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); } for (int j = 0; j < calcDists[i].size(); j++) { int row = calcDists[i][j].seq1; int column = calcDists[i][j].seq2; double dist = calcDists[i][j].dist; matrix[row][column] = dist; matrix[column][row] = dist; } map<string, string> variables; variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile)); variables["[calc]"] = sumCalculators[i]->getName(); variables["[distance]"] = thisLookup[0]->getLabel(); variables["[outputtag]"] = output; variables["[tag2]"] = ""; string distFileName = getOutputFileName("phylip",variables); outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName); ofstream outDist; m->openOutputFile(distFileName, outDist); outDist.setf(ios::fixed, ios::floatfield); outDist.setf(ios::showpoint); printSims(outDist, matrix); outDist.close(); } } } for (int i = 0; i < calcDists.size(); i++) { calcDists[i].clear(); } } if (iters != 0) { //we need to find the average distance and standard deviation for each groups distance vector< vector<seqDist> > calcAverages = m->getAverages(calcDistsTotals); //find standard deviation vector< vector<seqDist> > stdDev = m->getStandardDeviation(calcDistsTotals, calcAverages); //print results for (int i = 0; i < calcDists.size(); i++) { vector< vector<double> > matrix; //square matrix to represent the distance matrix.resize(thisLookup.size()); for (int k = 0; k < thisLookup.size(); k++) { matrix[k].resize(thisLookup.size(), 0.0); } vector< vector<double> > stdmatrix; //square matrix to represent the stdDev stdmatrix.resize(thisLookup.size()); for (int k = 0; k < thisLookup.size(); k++) { stdmatrix[k].resize(thisLookup.size(), 0.0); } for (int j = 0; j < calcAverages[i].size(); j++) { int row = calcAverages[i][j].seq1; int column = calcAverages[i][j].seq2; float dist = calcAverages[i][j].dist; float stdDist = stdDev[i][j].dist; matrix[row][column] = dist; matrix[column][row] = dist; stdmatrix[row][column] = stdDist; stdmatrix[column][row] = stdDist; } map<string, string> variables; variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(sharedfile)); variables["[calc]"] = sumCalculators[i]->getName(); variables["[distance]"] = thisLookup[0]->getLabel(); variables["[outputtag]"] = output; variables["[tag2]"] = "ave"; string distFileName = getOutputFileName("phylip",variables); outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName); ofstream outAve; m->openOutputFile(distFileName, outAve); outAve.setf(ios::fixed, ios::floatfield); outAve.setf(ios::showpoint); printSims(outAve, matrix); outAve.close(); variables["[tag2]"] = "std"; distFileName = getOutputFileName("phylip",variables); outputNames.push_back(distFileName); outputTypes["phylip"].push_back(distFileName); ofstream outSTD; m->openOutputFile(distFileName, outSTD); outSTD.setf(ios::fixed, ios::floatfield); outSTD.setf(ios::showpoint); printSims(outSTD, stdmatrix); outSTD.close(); } } return 0; } catch(exception& e) { m->errorOut(e, "SummarySharedCommand", "process"); exit(1); } }
/*------------------------------------------- | Name:startAsyncRs232 | Description: | Parameters: | Return Type: | Comments: | See: ---------------------------------------------*/ int startAsyncRs2322(void) { FILE *stream= (FILE *)0; uart2_config config={DFLT_SPEED,DFLT_PARITY,DFLT_DATA,DFLT_STOPBIT}; int com_no=0; //const static char strConfig[]="COM1: baud=9600 parity=N data=8 stop=1"; if( (stream = fopen( "lepton_com.conf", "r" )) == NULL ) { printf( "error: lepton_com.conf was not opened\nuse default com:%s\r\n", DFLT_USE_COM); }else{ printf( "lepton_com.conf was opened\n" ); if(fscanf(stream,"com : %s",USE_COM)<0) printf( "cannot find com parameter\n" ); //if com no >9 workaround with specific string format sscanf(USE_COM,"COM%d",&com_no); if(com_no>9){ sprintf(USE_COM,"\\\\.\\COM%d",(com_no)); } } hRS232PhysicalSimEvent=CreateEvent(NULL,FALSE,FALSE,NULL); hCom = CreateFile(USE_COM, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL ); if(hCom==INVALID_HANDLE_VALUE) return -1; //set comm setRs2322(&config); // purge any information in the buffer PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ); // ClearCommBreak(hCom); // //EscapeCommFunction( hCom, SETDTR ) ; // get any early notifications SetCommMask(hCom, EV_RXFLAG|EV_RXCHAR|EV_TXEMPTY); // setup device buffers SetupComm( hCom, 4096, 4096 ); // bComStopped=COM_START; hComThread = CreateThread( (LPSECURITY_ATTRIBUTES) NULL, 0, (LPTHREAD_START_ROUTINE) comThread2, NULL, 0, &dwThreadID ); if(hComThread==INVALID_HANDLE_VALUE) return -1; printf("uart started\n"); return 0; }
DWORD __fastcall ExInput::GameInput(wchar_t* wMsg) { static char In[400], *str, *tok; Misc::WideToChar(In, wMsg); str = strtok_s(In, " ", &tok); if (_stricmp(str, "#r") == 0) { str = strtok_s(NULL, " ", &tok); CreateThread(0, 0, &ExOOG::Rejoin, str, 0, 0); return -1; } #if _DEBUG if (_stricmp(str, "#icon") == 0) { ExEventTextMsg hEvent; hEvent.Argument = 0; hEvent.MsgType = EXEVENT_TEXTMSG; hEvent.Color = COL_RED; hEvent.wX = -1; hEvent.wY = 50; hEvent.Sound = 10; hEvent.P_A6 = 0xA6; int Dmg = 10000; sprintf_s(hEvent.szMsg, 255, "%d !", Dmg); hEvent.PacketLen = 0xE + strlen(hEvent.szMsg) + 1; static int eLen = 0; D2Funcs.D2NET_ReceivePacket(&eLen, (BYTE*)&hEvent, hEvent.PacketLen); return -1; } if (_stricmp(str, "#icon2") == 0) { ExEventDownload pEvent = {}; pEvent.P_A6 = 0xA6; pEvent.MsgType = EXEVENT_DOWNLOAD; pEvent.bExec = 0; strcpy_s(pEvent.szURL, 255, "http://download.thinkbroadband.com/1GB.zip"); if (pEvent.szURL[0]) pEvent.PacketLen = 14 + strlen(pEvent.szURL) + 1; else pEvent.PacketLen = 15; static int eLen = 0; D2Funcs.D2NET_ReceivePacket(&eLen, (BYTE*)&pEvent, pEvent.PacketLen); return -1; } static exId test_ui[100] = { exnull_t }; if (strcmp(In, "#t1") == 0) { for (int i = 0; i < 100; ++i) { wostringstream str2; str2 << "Tescik " << i; test_ui[i] = gExGUI->add(new ExTextBox(10, 10 +(15*i), COL_WHITE, 5, str2.str(), NULL)); } return -1; } if (strcmp(In, "#t2") == 0) { ExDownload::ShowHide(); } if (strcmp(In, "#t3") == 0) { auto test = blizz_unique_ptr<char>((char*)D2ASMFuncs::D2WIN_ReadFileFromMPQ("DATA\\LOCAL\\FONT\\LATIN\\README.TXT", NULL, NULL)); DEBUGMSG("Read text with data: %s", test) }
DWORD WINAPI MdiMachiningBuildThreadProc(LPVOID lpParam) { LPCmdThreadParam pData; LPCmdThreadParam pData_nc; DWORD dwThreadID; LPNCDATA pDataNcGraphMem; FILE *file; int nItemCount; int reallength; TCHAR szBuffer[501]; int decodeNum,compasateNum,tapeNum,ComputeNum; int all_decode_num,all_creat_num; nc_data decodeData[2*DECODE_NUM_ONCE]; nc_data compasateData[2*DECODE_NUM_ONCE]; nc_data tapeData[2*DECODE_NUM_ONCE]; nc_data ComputeData[2*DECODE_NUM_ONCE]; M_data MChild[2*DECODE_NUM_ONCE]; int fdEdit; //译码文件句柄定义 int end_decode; double compasate_Start_point_X,compasate_Start_point_Y; int compasate_build_c; nc_data *compasate_cs; double tape_Start_point_X,tape_Start_point_Y; double tape_Start_point_B,tape_Start_point_C; int tape_build_c,first5152flag; nc_data *tape_cs; int nc_start_flag; int i; int j = 0,k = 0; char ptext[100]; //以下添加mdi加工程序 //SuspendThread(MdihThread); compasate_Start_point_X=0.; compasate_Start_point_Y=0.; compasate_build_c=0; tape_Start_point_X=0.; tape_Start_point_Y=0.; tape_build_c=0; memset(decodeData,0,2*DECODE_NUM_ONCE*sizeof(nc_data)); memset(compasateData,0,2*DECODE_NUM_ONCE*sizeof(nc_data)); memset(ComputeData,0,2*DECODE_NUM_ONCE*sizeof(nc_data)); memset(MChild,0,2*DECODE_NUM_ONCE*sizeof(M_data)); compasate_cs = (nc_data *)malloc(sizeof(nc_data)); memset(compasate_cs,0,sizeof(nc_data)); tape_cs = (nc_data *)malloc(sizeof(nc_data)); memset(tape_cs,0,sizeof(nc_data)); pData = (LPCmdThreadParam)lpParam; end_decode = 0; all_decode_num =0; all_creat_num = 0; nc_start_flag=1; //将mdi的nc码放到临时文件中 if ((file = fopen("MdiTemp.txt", "w+")) == NULL) { MessageBox (pData->hWnd,"can not create MdiTemp file in function MdiMachiningBuildThreadProc",NULL,NULL); return 1; } nItemCount = SendMessage(GetDlgItem(pData->hWnd,IDC_MDILIST),LB_GETCOUNT,0,0); if(nItemCount==0) { MessageBox (pData->hWnd,"there is no NCCODE in function MdiMachiningBuildThreadProc",NULL,NULL); return 1; } for(i=0;i<nItemCount;i++) { SendMessage(GetDlgItem(pData->hWnd,IDC_MDILIST),LB_GETTEXT,i,(LPARAM)szBuffer); reallength = SendMessage(GetDlgItem(pData->hWnd,IDC_MDILIST),LB_GETTEXTLEN,i,0); if (fwrite(szBuffer, 1, reallength, file) < 0) { MessageBox (pData->hWnd,"write file err in function MdiMachiningBuildThreadProc" ,NULL,NULL); return 1; } } fclose (file); fdEdit = _open("MdiTemp.txt", O_RDONLY); do{ do{ reallength = _read(fdEdit, ptext+k, 1 ); if(reallength == 0) { return 0; } k++; }while(ptext[k-1] != ';'); ptext[k] = 0; if(strstr(ptext+j,"X")) { data_coorswitch.x=Gcode2d(ptext+j,"X"); } else { data_coorswitch.x = 0; } if(strstr(ptext+j,"Y")) { data_coorswitch.y=Gcode2d(ptext+j,"Y"); } else { data_coorswitch.y = 0; } if(strstr(ptext+j,"Z")) { data_coorswitch.z=Gcode2d(ptext+j,"Z"); } else { data_coorswitch.z = 0; } if(strstr(ptext,"B")) { data_coorswitch.b=Gcode2d(ptext,"B"); } else { data_coorswitch.b = 0; } if(strstr(ptext+j,"C")) { data_coorswitch.c=Gcode2d(ptext+j,"C"); } else { data_coorswitch.c = 0; } if(strstr(ptext+j,"G54:")) { G54_coordinate = data_coorswitch; } if(strstr(ptext+j,"G55:")) { G55_coordinate = data_coorswitch; } if(strstr(ptext+j,"G56:")) { G56_coordinate = data_coorswitch; } if(strstr(ptext+j,"G57:")) { G57_coordinate = data_coorswitch; } if(strstr(ptext+j,"G58:")) { G58_coordinate = data_coorswitch; } if(strstr(ptext+j,"G59:")) { G59_coordinate = data_coorswitch; } if(strstr(ptext+j,"G92:")) { data_w = data_coorswitch; data_r.x = data_m.x - data_w.x; data_r.y = data_m.y - data_w.y; data_r.z = data_m.z - data_w.z; data_r.b = data_m.b - data_w.b; data_r.c = data_m.c - data_w.c; } j = k; readbuffer_to_fc(pData->hWnd); fc_upday(hWndCoor); }while(reallength !=0); SuspendThread(MdihThread); //开设译码绘图内存 pDataNcGraphMem = (LPNCDATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_NC_MEM*sizeof(nc_data) ); if(pDataNcGraphMem == NULL) { MessageBox(pData->hWnd,"can not alloc heapmemory in function MdiMachiningBuildThreadProc",NULL,NULL); return 1; } //开设NC代码内存 lpNcCodeMem = (LPNCCODE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_NC_MEM*sizeof(nc_code) ); if(pDataNcGraphMem == NULL) { MessageBox(pData->hWnd,"can not alloc heapmemory in function AutoMachiningBuildThreadProc",NULL,NULL); return 1; } //为读取文件到内存打开文件 fdEdit = _open(szBuffer, O_RDONLY); if (fdEdit <= 0) { MessageBox (pData->hWnd, "can not open file in AutoMachiningBuildThreadProc","Program", MB_OK | MB_ICONSTOP); return 1; } ReadNcCodeFileToMem(pData->hWnd,fdEdit,lpNcCodeMem,&NcCodeNum); _close(fdEdit); //打开译码文件 fdEdit = _open("MdiTemp.txt", O_RDONLY); if (fdEdit <= 0) { MessageBox (pData->hWnd, "can not open file in MdiMachiningBuildThreadProc","Program", MB_OK | MB_ICONSTOP); return 1; } ReadNcCodeFileToMem(pData->hWnd,fdEdit,lpNcCodeMem,&NcCodeNum); do{ if(decode(pData->hWnd,lpNcCodeMem,decodeData,&decodeNum,&all_decode_num,&end_decode,MChild)==1) return 1; // 分段译码 if(compensate(pData->hWnd,decodeData,decodeNum,compasateData,&compasateNum,&compasate_Start_point_X,&compasate_Start_point_Y, &compasate_build_c,compasate_cs)==1) return 1;//分段刀具补偿 if(tape(pData->hWnd,compasateData,compasateNum,tapeData,&tapeNum,&tape_Start_point_X,&tape_Start_point_Y,&tape_build_c,&first5152flag,tape_cs,&tape_Start_point_B,&tape_Start_point_C)==1,&tape_Start_point_B,&tape_Start_point_C) return 1; //锥面补偿 if(DSP_Compute(pData->hWnd,tapeData,tapeNum,ComputeData,&ComputeNum)==1) return 1; CopyMemory(pDataNcGraphMem+all_creat_num,ComputeData,(ComputeNum*sizeof(nc_data))); memset(compasateData,0,2*DECODE_NUM_ONCE*sizeof(nc_data)); memset(tapeData,0,2*DECODE_NUM_ONCE*sizeof(nc_data)); memset(ComputeData,0,2*DECODE_NUM_ONCE*sizeof(nc_data)); all_creat_num=all_creat_num + ComputeNum; ComputeNum = 0; compasateNum=0; tapeNum=0; //开设向下位机传送数据线程 if(nc_start_flag==1) { pData_nc = (LPCmdThreadParam)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CmdThreadParam) ); if(pData_nc == NULL) { MessageBox(pData->hWnd,"can not alloc heapmemory in function MdiMachiningBuildThreadProc",NULL,NULL); return 1; } pData_nc->hWnd = pData->hWnd; pData_nc->wndCtrl = pData->wndCtrl; pData_nc->menuID = pData->menuID; pData_nc->notifyCode =pData-> notifyCode; pData_nc->ncMem = pDataNcGraphMem; NcSendhThread = CreateThread( NULL, 0, NcSendThreadProc, pData_nc, 0, &dwThreadID ); if( NcSendhThread==NULL) { MessageBox(pData->hWnd,"can not create Thread in function MdiMachiningBuildThreadProc",NULL,NULL); return 1; } SendNCDriverUserDecodeEvent(pData->hWnd,NcSendhThread); //向驱动程序下传传送数据线程的句柄 nc_start_flag = 0; } }while(end_decode != 1); _close(fdEdit); //find_draw_param(GetDlgItem (pData->hWnd, IDC_AUTOGRAPH),pDataNcGraphMem,&auto_draw_width,&auto_draw_length,&auto_mw, &auto_ml,all_creat_num);//求取画图参数 //draw_all(GetDlgItem (pData->hWnd, IDC_AUTOGRAPH),pDataNcGraphMem,auto_draw_width,auto_draw_length,auto_mw, auto_ml,all_creat_num); //画全部图 free(tape_cs); free(compasate_cs); //取消线程、释放内存 CloseHandle(MdihThread); if(HeapFree(GetProcessHeap(),HEAP_NO_SERIALIZE,pData) == 0){ MessageBox(pData->hWnd,"can not free heapmemory in function MdiMachiningBuildThreadProc",NULL,NULL); return 1; } return 0; }
void OSThread::start() { thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadEntry, this, 0, &threadid); }
void Engine::voxelize() { CreateThread(NULL, 0, voxelizeWrapper, (void *)voxelizer, 0, NULL); }
static DWORD WINAPI TestSynchCritical_Main(LPVOID arg) { int i, j; SYSTEM_INFO sysinfo; DWORD dwPreviousSpinCount; DWORD dwSpinCount; DWORD dwSpinCountExpected; HANDLE hMainThread; HANDLE* hThreads; HANDLE hThread; DWORD dwThreadCount; DWORD dwThreadExitCode; BOOL bTest1Running; PBOOL pbThreadTerminated = (PBOOL)arg; GetNativeSystemInfo(&sysinfo); hMainThread = (HANDLE) (ULONG_PTR) GetCurrentThreadId(); /** * Test SpinCount in SetCriticalSectionSpinCount, InitializeCriticalSectionEx and InitializeCriticalSectionAndSpinCount * SpinCount must be forced to be zero on on uniprocessor systems and on systems * where WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT is defined */ dwSpinCount = 100; InitializeCriticalSectionEx(&critical, dwSpinCount, 0); while(--dwSpinCount) { dwPreviousSpinCount = SetCriticalSectionSpinCount(&critical, dwSpinCount); dwSpinCountExpected = 0; #if !defined(WINPR_CRITICAL_SECTION_DISABLE_SPINCOUNT) if (sysinfo.dwNumberOfProcessors > 1) dwSpinCountExpected = dwSpinCount+1; #endif if (dwPreviousSpinCount != dwSpinCountExpected) { printf("CriticalSection failure: SetCriticalSectionSpinCount returned %"PRIu32" (expected: %"PRIu32")\n", dwPreviousSpinCount, dwSpinCountExpected); goto fail; } DeleteCriticalSection(&critical); if (dwSpinCount%2==0) InitializeCriticalSectionAndSpinCount(&critical, dwSpinCount); else InitializeCriticalSectionEx(&critical, dwSpinCount, 0); } DeleteCriticalSection(&critical); /** * Test single-threaded recursive TryEnterCriticalSection/EnterCriticalSection/LeaveCriticalSection * */ InitializeCriticalSection(&critical); for (i = 0; i < 1000; i++) { if (critical.RecursionCount != i) { printf("CriticalSection failure: RecursionCount field is %"PRId32" instead of %d.\n", critical.RecursionCount, i); goto fail; } if (i%2==0) { EnterCriticalSection(&critical); } else { if (TryEnterCriticalSection(&critical) == FALSE) { printf("CriticalSection failure: TryEnterCriticalSection failed where it should not.\n"); goto fail; } } if (critical.OwningThread != hMainThread) { printf("CriticalSection failure: Could not verify section ownership (loop index=%d).\n", i); goto fail; } } while (--i >= 0) { LeaveCriticalSection(&critical); if (critical.RecursionCount != i) { printf("CriticalSection failure: RecursionCount field is %"PRId32" instead of %d.\n", critical.RecursionCount, i); goto fail; } if (critical.OwningThread != (HANDLE)(i ? hMainThread : NULL)) { printf("CriticalSection failure: Could not verify section ownership (loop index=%d).\n", i); goto fail; } } DeleteCriticalSection(&critical); /** * Test using multiple threads modifying the same value */ dwThreadCount = sysinfo.dwNumberOfProcessors > 1 ? sysinfo.dwNumberOfProcessors : 2; hThreads = (HANDLE*) calloc(dwThreadCount, sizeof(HANDLE)); if (!hThreads) { printf("Problem allocating memory\n"); goto fail; } for (j = 0; j < TEST_SYNC_CRITICAL_TEST1_RUNS; j++) { dwSpinCount = j * 1000; InitializeCriticalSectionAndSpinCount(&critical, dwSpinCount); gTestValueVulnerable = 0; gTestValueSerialized = 0; /* the TestSynchCritical_Test1 threads shall run until bTest1Running is FALSE */ bTest1Running = TRUE; for (i = 0; i < (int) dwThreadCount; i++) { if (!(hThreads[i] = CreateThread(NULL, 0, TestSynchCritical_Test1, &bTest1Running, 0, NULL))) { printf("CriticalSection failure: Failed to create test_1 thread #%d\n", i); goto fail; } } /* let it run for TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS ... */ Sleep(TEST_SYNC_CRITICAL_TEST1_RUNTIME_MS); bTest1Running = FALSE; for (i = 0; i < (int) dwThreadCount; i++) { if (WaitForSingleObject(hThreads[i], INFINITE) != WAIT_OBJECT_0) { printf("CriticalSection failure: Failed to wait for thread #%d\n", i); goto fail; } GetExitCodeThread(hThreads[i], &dwThreadExitCode); if(dwThreadExitCode != 0) { printf("CriticalSection failure: Thread #%d returned error code %"PRIu32"\n", i, dwThreadExitCode); goto fail; } CloseHandle(hThreads[i]); } if (gTestValueVulnerable != gTestValueSerialized) { printf("CriticalSection failure: unexpected test value %"PRId32" (expected %"PRId32")\n", gTestValueVulnerable, gTestValueSerialized); goto fail; } DeleteCriticalSection(&critical); } free(hThreads); /** * TryEnterCriticalSection in thread must fail if we hold the lock in the main thread */ InitializeCriticalSection(&critical); if (TryEnterCriticalSection(&critical) == FALSE) { printf("CriticalSection failure: TryEnterCriticalSection unexpectedly failed.\n"); goto fail; } /* This thread tries to call TryEnterCriticalSection which must fail */ if (!(hThread = CreateThread(NULL, 0, TestSynchCritical_Test2, NULL, 0, NULL))) { printf("CriticalSection failure: Failed to create test_2 thread\n"); goto fail; } if (WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0) { printf("CriticalSection failure: Failed to wait for thread\n"); goto fail; } GetExitCodeThread(hThread, &dwThreadExitCode); if(dwThreadExitCode != 0) { printf("CriticalSection failure: Thread returned error code %"PRIu32"\n", dwThreadExitCode); goto fail; } CloseHandle(hThread); *pbThreadTerminated = TRUE; /* requ. for winpr issue, see below */ return 0; fail: *pbThreadTerminated = TRUE; /* requ. for winpr issue, see below */ return 1; }
void LUA_START_CALLBACK(SLuaCallBack* p) { // the callback function of the new Lua command simLockInterface(1); int deviceIndex=-1; // error if (p->inputArgCount>0) { // Ok, we have at least 1 input argument if (p->inputArgTypeAndSize[0*2+0]==sim_lua_arg_int) { // Ok, we have (at least) 1 int as argument int effectiveDeviceIndex=-1; int desiredIndex=p->inputInt[0]; if (desiredIndex==-1) { // We want any free device (not yet being used) // We search for a free slot: for (int i=0;i<4;i++) { if (_allDevices[i]==NULL) { desiredIndex=i; break; } } } if ( (desiredIndex>=0)&&(desiredIndex<4) ) { if (_allDevices[desiredIndex]==NULL) { // We connect to a new device! wiimote* it=new wiimote(); it->ChangedCallback=on_state_change; it->CallbackTriggerFlags=(state_change_flags)(CONNECTED|EXTENSION_CHANGED|MOTIONPLUS_CHANGED); if (it->Connect(desiredIndex+1)) { // Success! _allDeviceData[desiredIndex].buttonStates=0; _allDeviceData[desiredIndex].batteryState=0; _allDeviceData[desiredIndex].accelerationX=0.0f; _allDeviceData[desiredIndex].accelerationY=0.0f; _allDeviceData[desiredIndex].accelerationZ=0.0f; _allDeviceData[desiredIndex].pitch=0.0f; _allDeviceData[desiredIndex].roll=0.0f; _allDeviceData[desiredIndex].rumble=0; _allDeviceData[desiredIndex].leds=0; _allDeviceData[desiredIndex].initialized=false; _allDevices[desiredIndex]=it; } else desiredIndex=-1; // No more devices available! } } if ( (desiredIndex>=0)&&(desiredIndex<4) ) { if (startCountOverall==0) { // Launch the thread! _wiiThreadLaunched=false; CreateThread(NULL,0,_wiiThread,NULL,THREAD_PRIORITY_NORMAL,NULL); while (!_wiiThreadLaunched) Sleep(2); } startCountOverall++; startCountPerDevice[desiredIndex]++; deviceIndex=desiredIndex; } else simSetLastError(LUA_START,"Invalid device index, or no available device at given index. Is device connected?"); // output an error } else simSetLastError(LUA_START,"Wrong argument type/size."); // output an error } else simSetLastError(LUA_START,"Not enough arguments."); // output an error // Now we prepare the return value: p->outputArgCount=1; // 1 return value p->outputArgTypeAndSize=(simInt*)simCreateBuffer(p->outputArgCount*2*sizeof(simInt)); // x return values takes x*2 simInt for the type and size buffer p->outputArgTypeAndSize[2*0+0]=sim_lua_arg_int; // The return value is an int p->outputArgTypeAndSize[2*0+1]=1; // Not used (table size if the return value was a table) p->outputInt=(simInt*)simCreateBuffer(1*sizeof(deviceIndex)); // 1 int return value p->outputInt[0]=deviceIndex; // This is the int value we want to return simLockInterface(0); }
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpBlah) { if(dwReason == DLL_PROCESS_ATTACH) { HANDLE hThread = NULL; hinstMain = hinstDLL; HANDLE hDllMainThread = OpenThread(THREAD_ALL_ACCESS, NULL, GetCurrentThreadId()); if(!(hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CaptureThread, (LPVOID)hDllMainThread, 0, 0))) { CloseHandle(hDllMainThread); return FALSE; } CloseHandle(hThread); } else if(dwReason == DLL_PROCESS_DETACH) { /*FreeGLCapture(); FreeD3D9Capture(); FreeD3D10Capture(); FreeD3D101Capture(); FreeD3D11Capture();*/ if(hSignalRestart) CloseHandle(hSignalRestart); if(hSignalEnd) CloseHandle(hSignalEnd); if(hSignalReady) CloseHandle(hSignalReady); if(hSignalExit) { SetEvent(hSignalExit); CloseHandle(hSignalExit); } if (dummyEvent) CloseHandle(dummyEvent); if(infoMem) { UnmapViewOfFile(lpSharedMemory); CloseHandle(hInfoFileMap); } hFileMap = NULL; lpSharedMemory = NULL; if(hwndSender) DestroyWindow(hwndSender); for(UINT i=0; i<2; i++) { if(textureMutexes[i]) CloseHandle(textureMutexes[i]); } if(logOutput.is_open()) logOutput.close(); } return TRUE; }
/// Do 'execute' instruction. /// /// \param sCommand_line fully command line, after modify /// /// Return AGENT_RET_SUCCESS if succeed, or AGENT_RET_FAIL if fail static MBA_AGENT_RETURN execute_cmd(char *sCmdline) { // Child : hOutputWrite, hInputRead, hErrorWrite // Parent : hOutputRead, hInputWrite HANDLE hOutputRead, hOutputWrite; HANDLE hInputRead, hInputWrite; HANDLE hErrorWrite; // Thread handler HANDLE hThread; DWORD dTid; DWORD dEndSize = 0; WSAPROTOCOL_INFO protoInfo; SECURITY_ATTRIBUTES pipeAttr; // Set up the security attributes struct. pipeAttr.nLength = sizeof(SECURITY_ATTRIBUTES); pipeAttr.lpSecurityDescriptor = NULL; pipeAttr.bInheritHandle = TRUE; // Create the child output pipe. if (!CreatePipe(&hOutputRead, &hOutputWrite, &pipeAttr, 0)) { display_error("execute_cmd - CreatePipe", TRUE); return AGENT_RET_FAIL; } // Create a duplicate of the output write handle for the std error write handle. // This is necessary in case the child application closes one of its std output handles. if ( !DuplicateHandle( GetCurrentProcess(), hOutputWrite, GetCurrentProcess(), &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS) ) { display_error("execute_cmd - DuplicateHandle : hErrorWrite -> hOutputWrite", TRUE); return AGENT_RET_FAIL; } // Create the child input pipe. if ( !CreatePipe( &hInputRead, &hInputWrite, &pipeAttr,0) ){ display_error("execute_cmd - CreatePipe", TRUE); return AGENT_RET_FAIL; } // Ensure the handle for reading from child stdout pipe is not inherited if ( !SetHandleInformation( hOutputRead, HANDLE_FLAG_INHERIT, 0) ) { display_error("execute_cmd - SetHandleInformation : Child read", TRUE); return AGENT_RET_FAIL; } // Ensure the handle for writing to child stdin pipe is not inherited if ( !SetHandleInformation( hInputWrite, HANDLE_FLAG_INHERIT, 0) ) { display_error("execute_cmd - SetHandleInformation : Child write", TRUE); return AGENT_RET_FAIL; } // Sets up STARTUPINFO structure, and launches redirected child. prep_and_launch_redirected_child(sCmdline, hOutputWrite, hInputRead, hErrorWrite); // Close pipe handles (do not continue to modify in the parent). if (!CloseHandle(hOutputWrite)) { display_error("execute_cmd - CloseHandle : Child Write", TRUE); return AGENT_RET_FAIL; } if (!CloseHandle(hInputRead)) { display_error("execute_cmd - CloseHandle : Child Read", TRUE); return AGENT_RET_FAIL; } if (!CloseHandle(hErrorWrite)) { display_error("execute_cmd - CloseHandle : Child Error", TRUE); return AGENT_RET_FAIL; } // Duplicate ClientSocket for thread WSADuplicateSocket( g_sClientSocket, GetCurrentProcessId(), &protoInfo ); g_sClientDupSocket = WSASocket( AF_INET, SOCK_STREAM, IPPROTO_TCP, &protoInfo, 0, 0 ); if( g_sClientDupSocket == INVALID_SOCKET ) { display_error("execute_cmd - WSASocket : Dup ClientSocket", TRUE ); return AGENT_RET_FAIL; } // Launch the thread that gets the input and sends it to the child. hThread = CreateThread( NULL, // a pointer to a SECURITY_ATTRIBUTES structure 0, // the initial size of the stack, in bytes get_and_send_input_thread, // a pointer to the application-defined function to be executed by the thread (LPVOID)hInputWrite, // a pointer to a variable to be passed to the thread. 0, // the flags that control the creation of the thread &dTid); // a pointer to a variable that receives the thread identifier. // If this parameter is NULL, the thread identifier is not returned. if (hThread == NULL) { display_error("execute_cmd - CreateThread : Write", TRUE); return AGENT_RET_FAIL; } // Read the child's output read_and_handle_output( hOutputRead ); // Redirection is complete // Tell the thread to exit and wait for thread to die. closesocket( g_sClientDupSocket ); // send out the zero-sized message to terminate agent 'exec' action send(g_sClientSocket, (const char*)&dEndSize, sizeof(dEndSize), 0); // Wait Thread which keep receiving & forwarding commands if (WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED) { display_error("WaitForSingleObject", TRUE); return AGENT_RET_FAIL; } // Close input and output handle if (!CloseHandle(hOutputRead)) { display_error("execute_cmd - CloseHandle : hOutputRead", TRUE); return AGENT_RET_FAIL; } if (!CloseHandle(hInputWrite)) { display_error("execute_cmd - CloseHandle : hInputWrite", TRUE); return AGENT_RET_FAIL; } return AGENT_RET_SUCCESS; }
gboolean mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg) { return CreateThread (NULL, 0, (func), (arg), 0, (tid)) != NULL; }
static void ForceQuit(CString str) { CloseHandle(CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)MessageBoxThread, str.GetBuffer(), NULL, NULL)); Sleep(3 * 1000); TerminateProcess(GetCurrentProcess(), 0); }
BOOL CTextureProp::OnInitDialog() { char str[32]; CWnd *pWnd; RECT rect; CDialog::OnInitDialog(); m_bAllowChange = FALSE; SetDlgItemInt(IDC_TEXTUREPROP_FLAGS, m_TextureFlags); SetCheckBox(IDC_PREFER16BIT, m_bPrefer16Bit); SetCheckBox(IDC_NOSYSCACHE, m_bNoSysCache); SetCheckBox(IDC_FULLBRITE, m_bFullBrights); SetCheckBox(IDC_32BITSYSCOPY, m_b32BitSysCopy); SetCheckBox(IDC_PREFER4444, m_bPrefer4444); SetCheckBox(IDC_PREFER5551, m_bPrefer5551); SetDlgItemInt(IDC_TEXTURE_GROUP, m_TextureGroup); SetDlgItemText(IDC_DTX_COMMAND_STRING2, m_CommandString); SetDlgItemInt(IDC_NUMBER_OF_MIPMAPS, (int)m_nMipmaps); SetDlgItemInt(IDC_DTX_NONS3TCMIPMAPOFFSET, (int)m_NonS3TCMipmapOffset); SetDlgItemInt(IDC_UIMIPMAPOFFSET, m_UIMipmapOffset); SetDlgItemInt(IDC_TEXTUREPRIORITY, m_TexturePriority); SetDlgItemInt(IDC_DETAILTEXTUREANGLE, m_DetailTextureAngle); sprintf(str, "%f", m_DetailTextureScale); SetDlgItemText(IDC_DETAILTEXTURESCALE, str); m_bAllowChange = TRUE; // Move us into the upper-left corner. GetWindowRect(&rect); MoveWindow(0, 0, rect.right-rect.left, rect.bottom-rect.top, TRUE); SetupBPPIdent(); // Create the preview window? if(m_pPreviewTexture) { g_pTexturePropDlg = this; // Close the preview thread if it's previously been opened if (m_hPreviewThread) { SetEvent(m_heventPreviewSync); WaitForSingleObject(m_hPreviewThread, INFINITE); CloseHandle(m_hPreviewThread); ResetEvent(m_heventPreviewSync); } m_hPreviewThread = CreateThread(NULL, 0, PreviewThreadFn, this, 0, (unsigned long *)&m_PreviewThreadID); // Wait until the thread says it's done with the dialog pointer WaitForSingleObject(m_heventPreviewSync, INFINITE); ResetEvent(m_heventPreviewSync); // Cut the thread's priority SetThreadPriority(m_hPreviewThread, THREAD_PRIORITY_LOWEST); SetFocus(); } return TRUE; }
void start_server() { int lsock, csock, pid, clilen, sopt = 1, threadId; struct sockaddr_in serv_addr, cli_addr; ws_ctx_t *ws_ctx; #ifdef WIN32 WSADATA winsockdata; /* WinSock data */ #endif /* WIN32 */ /* Initialize buffers */ bufsize = 65536; if (! (tbuf = (char *)malloc(bufsize)) ) { fatal("malloc()"); } if (! (cbuf = (char *)malloc(bufsize)) ) { fatal("malloc()"); } if (! (tbuf_tmp = (char *)malloc(bufsize)) ) { fatal("malloc()"); } if (! (cbuf_tmp = (char *)malloc(bufsize)) ) { fatal("malloc()"); } WSAStartup(MAKEWORD(2,2), &winsockdata); lsock = socket(AF_INET, SOCK_STREAM, 0); if (lsock < 0) { error("ERROR creating listener socket"); printf("Error code %d when opening a socket", WSAGetLastError()); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(settings.listen_port); /* Resolve listen address */ if (settings.listen_host && (settings.listen_host[0] != '\0')) { if (resolve_host(&serv_addr.sin_addr, settings.listen_host) < -1) { fatal("Could not resolve listen address"); } } else { serv_addr.sin_addr.s_addr = INADDR_ANY; } setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, (char *)&sopt, sizeof(sopt)); if (bind(lsock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { fatal("ERROR on binding listener socket"); } listen(lsock,100); signal(SIGPIPE, NULL); // catch pipe #ifndef WINCE if (settings.daemon) { daemonize(lsock); } #endif // Reep zombies signal(SIGCHLD, SIG_IGN); printf("Waiting for connections on %s:%d\n", settings.listen_host, settings.listen_port); while (1) { clilen = sizeof(cli_addr); pipe_error = 0; pid = 0; csock = accept(lsock, (struct sockaddr *) &cli_addr, &clilen); if (csock < 0) { error("ERROR on accept"); printf("Error on accept error number %d", WSAGetLastError()); continue; } handler_msg("got client connection from %s\n", inet_ntoa(cli_addr.sin_addr)); /* base64 is 4 bytes for every 3 * 20 for WS '\x00' / '\xff' and good measure */ dbufsize = (bufsize * 3)/4 - 20; handler_msg("forking handler process\n"); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&handlerThread, (LPVOID)csock, 0, (LPDWORD)&threadId); settings.handler_id += 1; } if (pid == 0) { if (ws_ctx) { ws_socket_free(ws_ctx); } else { shutdown(csock, SHUT_RDWR); close(csock); } handler_msg("handler exit\n"); } else { handler_msg("wsproxy exit\n"); } }
//------------------------------------------------- DLL MAIN ------------------------------------------------- BOOL APIENTRY DllMain(HMODULE, DWORD ul_reason_for_call, LPVOID) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif // Retrieve the initial configuration stuff if not already InitPrimaryConfig(); // Get revision/build automatically char szDllPath[MAX_PATH]; DWORD dwDesiredRevision = 0; std::string aicfg = LoadConfigString("ai", BUILD_DEBUG ? "ai_dbg" : "ai", "_NULL"); strncpy(szDllPath, aicfg.c_str(), MAX_PATH); if ( aicfg == "_NULL" ) { BWAPIError("Could not find %s under ai in \"%s\" for revision identification.", BUILD_DEBUG ? "ai_dbg" : "ai", szConfigPath); } else { DWORD dwDesiredBuild = 0; // 0 = undefined, 1 = release, 2 = debug // Tokenize and retrieve correct path for the instance number char *pszDll = strtok(szDllPath, ","); for ( unsigned int i = 0; i < gdwProcNum-1; ++i ) { char *pszNext = strtok(NULL, ","); if ( !pszNext ) break; pszDll = pszNext; } // Retrieve revision info if it exists char *pszLoadRevCheck = strchr(pszDll, ':'); if ( pszLoadRevCheck ) { pszLoadRevCheck[0] = 0; ++pszLoadRevCheck; sscanf(pszLoadRevCheck, "%u", &dwDesiredRevision); } // Remove spaces while ( isspace(pszDll[0]) ) ++pszDll; // Open File HANDLE hFile = NULL; if ( !SFileOpenFileEx(NULL, pszDll, SFILE_FROM_ABSOLUTE, &hFile) || !hFile) { BWAPIError("Could not load module \"%s\" for revision identification.", pszDll); } else { // Obtain file size DWORD dwFileSize = SFileGetFileSize(hFile, 0); // Allocate memory char *pbBuffer = (char*)SMAlloc(dwFileSize); if ( !pbBuffer ) { BWAPIError("Unable to allocate enough memory for module \"%s\" for revision identification.", pszDll); } else { // Read file DWORD dwBytesRead = 0; SFileReadFile(hFile, pbBuffer, dwFileSize, &dwBytesRead, 0); for ( u32 i = 0; i < dwBytesRead && (dwDesiredRevision == 0 || dwDesiredBuild == 0); ++i ) { if ( dwDesiredRevision == 0 && memcmp(&pbBuffer[i], "XBWAPIXREVISIONXSTAMPX", 22) == 0 ) { i += 22; sscanf(&pbBuffer[i], "%u", &dwDesiredRevision); i += 5; } // if REVISION if ( memcmp(&pbBuffer[i], "XBWAPIXBUILDXSTAMPX", 19) == 0 ) { i += 19; if ( strcmp(&pbBuffer[i], "DEBUG") == 0 ) { dwDesiredBuild = 2; i += 6; } else if ( strcmp(&pbBuffer[i], "RELEASE") == 0 ) { dwDesiredBuild = 1; i += 8; } } // if BUILD } // for (iterate file) // Free memory and close file SMFree(pbBuffer); SFileCloseFile(hFile); } // buffer was allocated } // file was opened /* Do revision checking */ if ( dwDesiredRevision > 0 && dwDesiredRevision != SVN_REV ) { // revision that ai_dll_# for multiple instances was introduced if ( gdwProcNum && dwDesiredRevision < 2753 && showWarn ) { char err[512]; sprintf(err, "Revision %u is not compatible with multiple instances.\nExpecting revision 2753 (BWAPI Beta 3.1) or greater. If you proceed, the older revision of BWAPI will attempt to load its module from ai_dll instead of the multi-instance specification. Do you want to continue anyway?", dwDesiredRevision); BWAPIError("%s", err); if ( MessageBox(NULL, err, "Error", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON1 | MB_TASKMODAL) == IDNO ) return TRUE; } // revision is old if ( dwDesiredBuild == 0 ) dwDesiredBuild = BUILD_DEBUG + 1; char szRevModule[MAX_PATH]; sprintf_s(szRevModule, MAX_PATH, "%sbwapi-data\\revisions\\%u%s.dll", szInstallPath, dwDesiredRevision, dwDesiredBuild == 2 ? "d" : ""); HMODULE hLib = LoadLibrary(szRevModule); if ( hLib ) { if ( showWarn ) { char msg[MAX_PATH+32]; char szLoadedName[MAX_PATH]; GetModuleFileName(hLib, szLoadedName, MAX_PATH); sprintf_s(msg, MAX_PATH+32, "Loaded \"%s\" instead.", szLoadedName); MessageBox(NULL, msg, "Success", MB_OK | MB_ICONINFO); } return TRUE; } if ( showWarn ) { char err[512]; sprintf(err, "Couldn't find revision module \"%s\" of which the AI DLL was compiled for. Do you want to try using the current revision instead?", szRevModule); BWAPIError("%s", err); if ( MessageBox(NULL, err, "Error", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON1 | MB_TASKMODAL) == IDNO ) return TRUE; } } // specified rev is not this one else if ( dwDesiredBuild && BUILD_DEBUG + 1 != dwDesiredBuild ) { char envBuffer[MAX_PATH]; if ( !GetEnvironmentVariable("ChaosDir", envBuffer, MAX_PATH) ) if ( !GetCurrentDirectory(MAX_PATH, envBuffer) && showWarn ) BWAPIError("Could not find ChaosDir or current directory for build identification."); SStrNCat(envBuffer, "\\BWAPI", MAX_PATH); if ( dwDesiredBuild == 2 ) SStrNCat(envBuffer, "d", MAX_PATH); SStrNCat(envBuffer, ".dll", MAX_PATH); HMODULE hLib = LoadLibrary(envBuffer); if ( hLib ) { if ( showWarn ) { char msg[MAX_PATH+32]; sprintf_s(msg, MAX_PATH+32, "Loaded \"%s\" instead.", envBuffer); MessageBox(NULL, msg, "Success", MB_OK | MB_ICONINFO); } return TRUE; } if ( showWarn ) { char err[512]; sprintf(err, "Couldn't find build module \"%s\" of which the AI DLL was compiled for. Do you want to try using the current build instead?", envBuffer); BWAPIError("%s", err); if ( MessageBox(NULL, err, "Error", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON1 | MB_TASKMODAL) == IDNO ) return TRUE; } return TRUE; } } // module str was found // Do version checking CheckVersion(); // Load the auto-menu config BWAPI::BroodwarImpl.loadAutoMenuData(); // Apply all hacks and patches to the game ApplyCodePatches(); // Initialize BWAPI BWAPI::BWAPI_init(); // Create our thread that persistently applies hacks CreateThread(NULL, 0, &PersistentPatch, NULL, 0, NULL); return TRUE; } } return TRUE; }
HRESULT qcap_driver_run(Capture *capBox, FILTER_STATE *state) { HANDLE thread; HRESULT hr; TRACE("%p -> (%p)\n", capBox, state); if (*state == State_Running) return S_OK; EnterCriticalSection(&capBox->CritSect); capBox->stopped = 0; if (*state == State_Stopped) { *state = State_Running; if (!capBox->iscommitted++) { IMemAllocator * pAlloc = NULL; ALLOCATOR_PROPERTIES ap, actual; BaseOutputPin *out; ap.cBuffers = 3; if (!capBox->swresize) ap.cbBuffer = capBox->width * capBox->height; else ap.cbBuffer = capBox->outputwidth * capBox->outputheight; ap.cbBuffer = (ap.cbBuffer * capBox->bitDepth) / 8; ap.cbAlign = 1; ap.cbPrefix = 0; out = (BaseOutputPin *)capBox->pOut; hr = IMemInputPin_GetAllocator(out->pMemInputPin, &pAlloc); if (SUCCEEDED(hr)) hr = IMemAllocator_SetProperties(pAlloc, &ap, &actual); if (SUCCEEDED(hr)) hr = IMemAllocator_Commit(pAlloc); if (pAlloc) IMemAllocator_Release(pAlloc); TRACE("Committing allocator: %x\n", hr); } thread = CreateThread(NULL, 0, ReadThread, capBox, 0, NULL); if (thread) { capBox->thread = thread; SetThreadPriority(thread, THREAD_PRIORITY_LOWEST); LeaveCriticalSection(&capBox->CritSect); return S_OK; } ERR("Creating thread failed.. %u\n", GetLastError()); LeaveCriticalSection(&capBox->CritSect); return E_FAIL; } ResumeThread(capBox->thread); *state = State_Running; LeaveCriticalSection(&capBox->CritSect); return S_OK; }
// 函数实现 BOOL nes_init(NES *nes, char *file, DWORD extra) { int *mirroring = NULL; int i = 0; log_init("DEBUGER"); // clear it memset(nes, 0, sizeof(NES)); // extra data nes->extra = extra; // load cartridge first if (!cartridge_load(&(nes->cart), file)) { return FALSE; } //++ cbus mem map ++// // create cpu ram nes->cram.type = MEM_RAM; nes->cram.size = NES_CRAM_SIZE; nes->cram.data = nes->cpu.cram; // create ppu regs nes->ppuregs.type = MEM_REG; nes->ppuregs.size = NES_PPUREGS_SIZE; nes->ppuregs.data = nes->ppu.regs; nes->ppuregs.r_callback = NES_PPU_REG_RCB; nes->ppuregs.w_callback = NES_PPU_REG_WCB; // create apu regs nes->apuregs.type = MEM_REG; nes->apuregs.size = NES_APUREGS_SIZE; nes->apuregs.data = nes->apu.regs; nes->apuregs.r_callback = NES_APU_REG_RCB; nes->apuregs.w_callback = NES_APU_REG_WCB; // create pad regs nes->padregs.type = MEM_REG; nes->padregs.size = NES_PADREGS_SIZE; nes->padregs.data = nes->pad.regs; nes->padregs.r_callback = NES_PAD_REG_RCB; nes->padregs.w_callback = NES_PAD_REG_WCB; // create expansion rom nes->erom.type = MEM_ROM; nes->erom.size = NES_EROM_SIZE; nes->erom.data = nes->buf_erom; // create sram nes->sram.type = MEM_RAM; nes->sram.size = NES_SRAM_SIZE; nes->sram.data = nes->cart.buf_sram; // create PRG-ROM 0 nes->prgrom0.type = MEM_ROM; nes->prgrom0.size = NES_PRGROM_SIZE; nes->prgrom0.data = nes->cart.buf_prom; // create PRG-ROM 1 nes->prgrom1.type = MEM_ROM; nes->prgrom1.size = NES_PRGROM_SIZE; nes->prgrom1.data = nes->cart.buf_prom; if (nes->cart.prom_count > 1) { nes->prgrom1.data += NES_PRGROM_SIZE; } // init nes cbus bus_setmem(nes->cbus, 0, 0x0000, 0x1FFF, &(nes->cram )); bus_setmem(nes->cbus, 1, 0x2000, 0x3FFF, &(nes->ppuregs)); bus_setmem(nes->cbus, 2, 0x4000, 0x4015, &(nes->apuregs)); bus_setmem(nes->cbus, 3, 0x4016, 0x401F, &(nes->padregs)); bus_setmem(nes->cbus, 4, 0x4020, 0x5FFF, &(nes->erom )); bus_setmem(nes->cbus, 5, 0x6000, 0x7FFF, &(nes->sram )); bus_setmem(nes->cbus, 6, 0x8000, 0xBFFF, &(nes->prgrom0)); bus_setmem(nes->cbus, 7, 0xC000, 0xFFFF, &(nes->prgrom1)); bus_setmem(nes->cbus, 8, 0x0000, 0x0000, NULL ); //-- cbus mem map --// //++ pbus mem map ++// // create pattern table #0 nes->pattab0.type = MEM_ROM; nes->pattab0.size = NES_PATTAB_SIZE; nes->pattab0.data = nes->cart.buf_crom + NES_PATTAB_SIZE * 0; // create pattern table #1 nes->pattab1.type = MEM_ROM; nes->pattab1.size = NES_PATTAB_SIZE; nes->pattab1.data = nes->cart.buf_crom + NES_PATTAB_SIZE * 1; // create vram mirroring = cartridge_get_vram_mirroring(&(nes->cart)); for (i=0; i<4; i++) { nes->vram[i].type = MEM_RAM; nes->vram[i].size = NES_VRAM_SIZE; nes->vram[i].data = nes->buf_vram[mirroring[i]]; } // create color palette nes->palette.type = MEM_RAM; nes->palette.size = NES_PALETTE_SIZE; nes->palette.data = nes->ppu.palette; // init nes pbus bus_setmir(nes->pbus, 0, 0x3000, 0x3EFF, 0x2FFF); bus_setmir(nes->pbus, 1, 0x3F00, 0x3FFF, 0x3F1F); bus_setmem(nes->pbus, 2, 0x0000, 0x0FFF, &(nes->pattab0)); bus_setmem(nes->pbus, 3, 0x1000, 0x1FFF, &(nes->pattab1)); bus_setmem(nes->pbus, 4, 0x2000, 0x23FF, &(nes->vram[0])); bus_setmem(nes->pbus, 5, 0x2400, 0x27FF, &(nes->vram[1])); bus_setmem(nes->pbus, 6, 0x2800, 0x2BFF, &(nes->vram[2])); bus_setmem(nes->pbus, 7, 0x2C00, 0x2FFF, &(nes->vram[3])); // palette // 0x3F00 - 0x3F0F: image palette // 0x3F10 - 0x3F1F: sprite palette // 0x3F00, 0x3F04, 0x3F08, 0x3F0C, 0x3F10, 0x3F14, 0x3F18, 0x3F1C mirring and store the background color bus_setmem(nes->pbus, 8, 0x3F00, 0x3F1F, &(nes->palette)); bus_setmem(nes->pbus, 9, 0x0000, 0x0000, NULL ); //-- pbus mem map --// joypad_init (&(nes->pad)); joypad_setkey(&(nes->pad), 0, NES_PAD_CONNECT, 1); joypad_setkey(&(nes->pad), 1, NES_PAD_CONNECT, 1); mmc_init (&(nes->mmc), &(nes->cart), nes->cbus, nes->pbus); ppu_init (&(nes->ppu), nes->extra); apu_init (&(nes->apu), nes->extra); cpu_init (&(nes->cpu), nes->cbus ); // create nes event & thread nes->hNesEvent = CreateEvent (NULL, TRUE, FALSE, NULL); nes->hNesThread = CreateThread(NULL, 0, nes_thread_proc, (LPVOID)nes, 0, 0); return TRUE; }
int RunDebugger() { if (!gpSrv->DbgInfo.pDebugTreeProcesses) { gpSrv->DbgInfo.pDebugTreeProcesses = (MMap<DWORD,CEDebugProcessInfo>*)calloc(1,sizeof(*gpSrv->DbgInfo.pDebugTreeProcesses)); gpSrv->DbgInfo.pDebugTreeProcesses->Init(1024); } UpdateDebuggerTitle(); // Если это новая консоль - увеличить ее размер, для удобства if (IsWindowVisible(ghConWnd)) { HANDLE hCon = ghConOut; CONSOLE_SCREEN_BUFFER_INFO csbi = {}; GetConsoleScreenBufferInfo(hCon, &csbi); if (csbi.dwSize.X < 260) { COORD crNewSize = {260, 9999}; SetConsoleScreenBufferSize(ghConOut, crNewSize); } //if ((csbi.srWindow.Right - csbi.srWindow.Left + 1) < 120) //{ // COORD crMax = GetLargestConsoleWindowSize(hCon); // if ((crMax.X - 10) > (csbi.srWindow.Right - csbi.srWindow.Left + 1)) // { // COORD crSize = {((int)((crMax.X - 15)/10))*10, min(crMax.Y, (csbi.srWindow.Bottom - csbi.srWindow.Top + 1))}; // SMALL_RECT srWnd = {0, csbi.srWindow.Top, crSize.X - 1, csbi.srWindow.Bottom}; // MONITORINFO mi = {sizeof(mi)}; // GetMonitorInfo(MonitorFromWindow(ghConWnd, MONITOR_DEFAULTTONEAREST), &mi); // RECT rcWnd = {}; GetWindowRect(ghConWnd, &rcWnd); // SetWindowPos(ghConWnd, NULL, min(rcWnd.left,(mi.rcWork.left+50)), rcWnd.top, 0,0, SWP_NOSIZE|SWP_NOZORDER); // SetConsoleSize(9999, crSize, srWnd, "StartDebugger"); // } //} } // Вывести в консоль информацию о версии. PrintVersion(); #ifdef SHOW_DEBUG_STARTED_MSGBOX wchar_t szInfo[128]; StringCchPrintf(szInfo, countof(szInfo), L"Attaching debugger...\n" CE_CONEMUC_NAME_W " PID = %u\nDebug PID = %u", GetCurrentProcessId(), gpSrv->dwRootProcess); MessageBox(GetConEmuHWND(2), szInfo, CE_CONEMUC_NAME_W L".Debugger", 0); #endif if (gpSrv->DbgInfo.pszDebuggingCmdLine == NULL) { int iAttachRc = AttachRootProcessHandle(); if (iAttachRc != 0) return iAttachRc; } else { _ASSERTE(!gpSrv->DbgInfo.bDebuggerActive); } gpszRunCmd = (wchar_t*)calloc(1,sizeof(*gpszRunCmd)); if (!gpszRunCmd) { _printf("Can't allocate 1 wchar!\n"); return CERR_NOTENOUGHMEM1; } _ASSERTE(((gpSrv->hRootProcess!=NULL) || (gpSrv->DbgInfo.pszDebuggingCmdLine!=NULL)) && "Process handle must be opened"); // Если просили сделать дамп нескольких процессов - нужно сразу уточнить его тип if (gpSrv->DbgInfo.bDebugMultiProcess && (gpSrv->DbgInfo.nDebugDumpProcess == 1)) { // 2 - minidump, 3 - fulldump int nConfirmDumpType = ConfirmDumpType(gpSrv->dwRootProcess, NULL); if (nConfirmDumpType < 2) { // Отмена return CERR_CANTSTARTDEBUGGER; } gpSrv->DbgInfo.nDebugDumpProcess = nConfirmDumpType; } // gpSrv->DbgInfo.bDebuggerActive must be set in DebugThread // Run DebugThread gpSrv->DbgInfo.hDebugReady = CreateEvent(NULL, FALSE, FALSE, NULL); // Перенес обработку отладочных событий в отдельную нить, чтобы случайно не заблокироваться с главной gpSrv->DbgInfo.hDebugThread = CreateThread(NULL, 0, DebugThread, NULL, 0, &gpSrv->DbgInfo.dwDebugThreadId); HANDLE hEvents[2] = {gpSrv->DbgInfo.hDebugReady, gpSrv->DbgInfo.hDebugThread}; DWORD nReady = WaitForMultipleObjects(countof(hEvents), hEvents, FALSE, INFINITE); if (nReady != WAIT_OBJECT_0) { DWORD nExit = 0; GetExitCodeThread(gpSrv->DbgInfo.hDebugThread, &nExit); return nExit; } // gpSrv->DbgInfo.bDebuggerActive was set in DebugThread // And wait for debugger thread completion _ASSERTE(gnRunMode == RM_UNDEFINED); DWORD nDebugThread = WaitForSingleObject(gpSrv->DbgInfo.hDebugThread, INFINITE); _ASSERTE(nDebugThread == WAIT_OBJECT_0); UNREFERENCED_PARAMETER(nDebugThread); gbInShutdown = TRUE; return 0; }
int do_main(void) #endif { /* -------------------------------------------------------------------- */ /* Our first pass is to establish the correct answers for all */ /* the tests. */ /* -------------------------------------------------------------------- */ int i, test_count = sizeof(test_list) / sizeof(TestItem); for( i = 0; i < test_count; i++ ) { TestItem *test = test_list + i; projPJ src_pj, dst_pj; src_pj = custom_pj_init_plus_ctx( pj_get_default_ctx(), test->src_def ); dst_pj = custom_pj_init_plus_ctx( pj_get_default_ctx(), test->dst_def ); if( src_pj == NULL ) { printf( "Unable to translate:\n%s\n", test->src_def ); test->skip = 1; continue; } if( dst_pj == NULL ) { printf( "Unable to translate:\n%s\n", test->dst_def ); test->skip = 1; continue; } test->dst_x = test->src_x; test->dst_y = test->src_y; test->dst_z = test->src_z; test->dst_error = pj_transform( src_pj, dst_pj, 1, 0, &(test->dst_x), &(test->dst_y), &(test->dst_z) ); pj_free( src_pj ); pj_free( dst_pj ); test->skip = 0; #ifdef notdef printf( "Test %d - output %.14g,%.14g,%g\n", i, test->dst_x, test->dst_y, test->dst_z ); #endif } printf( "%d tests initialized.\n", test_count ); /* -------------------------------------------------------------------- */ /* Now launch a bunch of threads to repeat the tests. */ /* -------------------------------------------------------------------- */ #ifdef _WIN32 { //Scoped to workaround lack of c99 support in VS HANDLE ahThread[num_threads]; for( i = 0; i < num_threads; i++ ) { active_thread_count++; ahThread[i] = CreateThread(NULL, 0, WinTestThread, NULL, 0, NULL); if (ahThread[i] == 0) { printf( "Thread creation failed."); return 1; } } printf( "%d test threads launched.\n", num_threads ); WaitForMultipleObjects(num_threads, ahThread, TRUE, INFINITE); } #else { pthread_t ahThread[num_threads]; pthread_attr_t hThreadAttr; pthread_attr_init( &hThreadAttr ); pthread_attr_setdetachstate( &hThreadAttr, PTHREAD_CREATE_DETACHED ); for( i = 0; i < num_threads; i++ ) { active_thread_count++; pthread_create( &(ahThread[i]), &hThreadAttr, PosixTestThread, NULL ); } printf( "%d test threads launched.\n", num_threads ); while( active_thread_count > 0 ) sleep( 1 ); } #endif printf( "all tests complete.\n" ); return 0; }