当前位置: 首页>>代码示例>>C++>>正文


C++ CreateThread函数代码示例

本文整理汇总了C++中CreateThread函数的典型用法代码示例。如果您正苦于以下问题:C++ CreateThread函数的具体用法?C++ CreateThread怎么用?C++ CreateThread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了CreateThread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: defined


//.........这里部分代码省略.........
                    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;
	}
开发者ID:Cryomics-Lab,项目名称:mothur,代码行数:101,代码来源:unweighted.cpp

示例2: CPath


//.........这里部分代码省略.........
		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;
}
开发者ID:JERUKA9,项目名称:xy-VSFilter,代码行数:101,代码来源:WebServer.cpp

示例3: main


//.........这里部分代码省略.........
        }
        
        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;
}
开发者ID:B-Rich,项目名称:osf_db,代码行数:101,代码来源:42606_0.c

示例4: CreateThread

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);
//.........这里部分代码省略.........
开发者ID:Edimartin,项目名称:edk-source,代码行数:101,代码来源:Thread.cpp

示例5: DlgProc

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 );
				
//.........这里部分代码省略.........
开发者ID:realrealkoc,项目名称:graduate,代码行数:101,代码来源:main.cpp

示例6: wsprintf

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)){
		}
//.........这里部分代码省略.........
开发者ID:kioku-systemk,项目名称:4kIntroMonitor,代码行数:101,代码来源:CSound.cpp

示例7: _tmain

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;
}
开发者ID:nikolain,项目名称:high-performance-string-float-random,代码行数:67,代码来源:cout_test_11.cpp

示例8: tandem


//.........这里部分代码省略.........
			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;
开发者ID:sebhtml,项目名称:rTANDEM,代码行数:67,代码来源:tandem.cpp

示例9: defined


//.........这里部分代码省略.........
                }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);
	}
}
开发者ID:barrykui,项目名称:mothur,代码行数:101,代码来源:preclustercommand.cpp

示例10: main

/*
 * 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 
      {
//.........这里部分代码省略.........
开发者ID:bowlofstew,项目名称:WinPcapExamples,代码行数:101,代码来源:ARPPing.cpp

示例11: Link_ThreadProc

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 ;
}
开发者ID:340211173,项目名称:hf-2011,代码行数:86,代码来源:Link.c

示例12: SharedRAbundVector


//.........这里部分代码省略.........
                //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];
                }
                
开发者ID:barrykui,项目名称:mothur,代码行数:66,代码来源:summarysharedcommand.cpp

示例13: startAsyncRs2322

/*-------------------------------------------
| 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;
}
开发者ID:lepton-distribution,项目名称:lepton,代码行数:78,代码来源:dev_win32uart2.c

示例14: strtok_s

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)
	}
开发者ID:m241dan,项目名称:D2Ex2,代码行数:70,代码来源:ExInput.cpp

示例15: MdiMachiningBuildThreadProc


//.........这里部分代码省略.........

			//打开译码文件
			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;
}
开发者ID:sundonga,项目名称:EDM_NC,代码行数:101,代码来源:mdiWndProc.cpp


注:本文中的CreateThread函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。