//DESCRIPTION: // This function creates the completion port and the requested number of threads. // If threads creation fails, the successfully created threads' handles are closed before returning. // //INPUT: // nbOfThreads - the number of threads to create // pWorkerThreads - the ouput pointer to the thread handle array // pAsync_config - the config struct // //OUTPUT: // TRUE for success // FALSE for error // BOOL AsyncFuzzer::InitializeThreadsAndCompletionPort() { BOOL bResult = FALSE; hIocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (ULONG_PTR)NULL, 0); if(hIocp) { // Associate the device handle to iocp bResult = (NULL!=CreateIoCompletionPort(hDev, hIocp, 0, 0)); if(bResult) { // Configure io completion port bResult = SetFileCompletionNotificationModes(hDev, FILE_SKIP_COMPLETION_PORT_ON_SUCCESS); if(bResult) { bResult = CreateThreads(); if(!bResult){ TPRINT(VERBOSITY_ERROR, _T("Failed to create worker threads\n")); } } else { TPRINT(VERBOSITY_ERROR, _T("Failed to configure iocompletion port with error %#.8x\n"), GetLastError()); } } else { TPRINT(VERBOSITY_ERROR, _T("Failed to associate device with iocompletion port with error %#.8x\n"), GetLastError()); } } else { TPRINT(VERBOSITY_ERROR, _T("Failed to create I/O completion port with error %#.8x\n"), GetLastError()); } return bResult; }
bool SocketMgr::StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, uint16 threads) { _threadCount = threads; if (_threadCount <= 0) { std::cout << "Network.Threads is wrong in your config file" << std::endl; return false; } try { _acceptor = new AsyncAcceptor(service, bindIp, port); } catch (boost::system::system_error const& err) { std::cout << "Exception caught in SocketMgr.StartNetwork (" << bindIp.c_str() << ":" << port << "): " << err.what(); return false; } _acceptor->AsyncAcceptManaged(&OnSocketAccept); _threads = CreateThreads(); for (int32 i = 0; i < _threadCount; ++i) _threads[i].Start(); return true; }
bool WaitObjectContainer::Wait(unsigned long milliseconds) { if (m_noWait || m_handles.empty()) return true; if (m_handles.size() > MAXIMUM_WAIT_OBJECTS) { // too many wait objects for a single WaitForMultipleObjects call, so use multiple threads static const unsigned int WAIT_OBJECTS_PER_THREAD = MAXIMUM_WAIT_OBJECTS-1; unsigned int nThreads = (m_handles.size() + WAIT_OBJECTS_PER_THREAD - 1) / WAIT_OBJECTS_PER_THREAD; if (nThreads > MAXIMUM_WAIT_OBJECTS) // still too many wait objects, maybe implement recursive threading later? throw Err("WaitObjectContainer: number of wait objects exceeds limit"); CreateThreads(nThreads); DWORD error = S_OK; for (unsigned int i=0; i<m_threads.size(); i++) { WaitingThreadData &thread = *m_threads[i]; while (!thread.waitingToWait) // spin until thread is in the initial "waiting to wait" state Sleep(0); if (i<nThreads) { thread.waitHandles = &m_handles[i*WAIT_OBJECTS_PER_THREAD]; thread.count = STDMIN(WAIT_OBJECTS_PER_THREAD, m_handles.size() - i*WAIT_OBJECTS_PER_THREAD); thread.error = &error; } else thread.count = 0; } ResetEvent(m_stopWaiting); PulseEvent(m_startWaiting); DWORD result = ::WaitForSingleObject(m_stopWaiting, milliseconds); if (result == WAIT_OBJECT_0) { if (error == S_OK) return true; else throw Err("WaitObjectContainer: WaitForMultipleObjects failed with error " + IntToString(error)); } SetEvent(m_stopWaiting); if (result == WAIT_TIMEOUT) return false; else throw Err("WaitObjectContainer: WaitForSingleObject failed with error " + IntToString(::GetLastError())); } else { DWORD result = ::WaitForMultipleObjects(m_handles.size(), &m_handles[0], FALSE, milliseconds); if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + m_handles.size()) return true; else if (result == WAIT_TIMEOUT) return false; else throw Err("WaitObjectContainer: WaitForMultipleObjects failed with error " + IntToString(::GetLastError())); } }
void FrameScheduler::DoOneFrame() { RunAllMonopolies(); CreateThreads(); RunMainThreadWork(); JoinAllThreads(); ResetAllWorkUnits(); WaitUntilNextFrame(); }
CThreadsManager::CThreadsManager( void ) { m_dwPoolSize = 0; m_dwBusyNum = 0; m_dwTestCount = 0; CreateThreads( THREADS_POOL_SIZE ); OspSemBCreate(&m_hSem); // m_iter = m_ThreadMap.begin(); }
// FIXME: This should probably just take in the FrSimCRegs instead of connecting via // a path FricXactor::FricXactor(std::string name, FricIf *intf) : FrVmXactor(name), inChan("inChan", 1), outChan("outChan", 1), _sif(FrSimIface::getSimIface()), _intf(intf) { CreateThreads(); }
/* RunTest This function runs a particular test for a number of times and reports the result. Parameters func A function with the test str A string with the test name Return Value None. This function prints the result */ void RunTest( void * ( * func)( void * ), char * str ) { // ------------------ Local Variables -------------------- int testnum; int passedtests; double timesum; pthread_t *threads; ThreadParameters_t *threadparameters; // ------------------- Initialization ------------------- passedtests = 0; timesum = 0; printf( "Now running [%s]\n", str ); // ------------------- Run Tests ------------------------ for ( testnum = 0; testnum < REPEATTESTS; testnum++ ) { my_mutex_init( &gMutex ); my_barrier_init( &gBarrier, gP ); CreateThreads( &threads, gP, func, &threadparameters ); JoinThreads( &threads, gP, &threadparameters ); my_mutex_destroy( &gMutex ); my_barrier_destroy( &gBarrier ); timesum += gElapsedTime; if ( gCorrectTest ) { passedtests++; printf( "+" ); fflush( stdout ); } else { printf( "-" ); fflush( stdout ); } } timesum /= REPEATTESTS; // ------------------- Print Outcome --------------------- printf( "\nTests passed: %d of %d. Average Time = %f (sec)\n", passedtests, REPEATTESTS, timesum ); }
void CThreadsManager::RunTask( CTaskObject* pTaskObject ) { if (FALSE == EnterLock()) { return; } //float fBusyNum = m_dwBusyNum * 100 / THRESHOLD_VALUE; if ( m_dwBusyNum<<1 >= m_dwPoolSize ) { CreateThreads( THREADS_STEP_INC ); } BOOL32 bFind = FALSE; // 直接从上一次的下一个开始查找 // ++m_iter; // for (; m_iter != m_ThreadMap.end(); ++m_iter) // { // CThreadInfo* pInfo = m_iter->second; // if (FALSE == pInfo->HasTask()) // { // pInfo->SetTask( pTaskObject ); // bFind = TRUE; // break; // } // ++g_FindCount; // } // 如果没有找到,则从头开始找 // if (FALSE == bFind) // { ThreadMap::iterator iter; for (iter = m_ThreadMap.begin(); iter != m_ThreadMap.end(); ++iter) { CThreadInfo* pInfo = iter->second; if (FALSE == pInfo->HasTask()) { pInfo->SetTask( pTaskObject ); break; } ++g_FindCount; } // } LeaveLock(); ++m_dwBusyNum; }
void ReadTorrentFile(char filename[]){ FILE* f = fopen(filename, "r"); char lines[3][20]; int i,length; for(i=0;i<3;i++){ fgets(lines[i],sizeof(lines[i]),f); length = strlen(lines[i]) - 1; if (lines[i][length] == '\n'){ lines[i][length] = '\0'; } } int hub = ConnectToHub(lines[0],lines[1]); if (hub){ pthread_t t; pthread_create(&t,NULL,(void*)PrintSize,NULL); GetNodList(hub); CreateThreads(lines[2]); } }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { Psx *psx = Psx::GetInstance(); CoInitialize(0); if (!CreateMainWindows(psx)) { return 1; } CreateThreads(psx); DWORD start = timeGetTime(); static char title[256]; while (!psx->quit) { if (psx->cpu->state == PSX_CPU_RUNNING) { if (timeGetTime()-start > 1000) { float speed = ((float)psx->cpu->mTotalCycles / Psx::CPU_CLOCK) * 100.0; sprintf_s(title, 256, "%.2f fps (%.2f%%)", (speed / 100.0) * 60.0, speed); SetWindowText(psx->mDispWnd->GetHwnd(), title); start = timeGetTime(); psx->cpu->mTotalCycles = 0; } } else { SetWindowText(psx->mDispWnd->GetHwnd(), "Paused"); } Window::ProcessMessages(); Sleep(10); } return psx->mMainWnd->GetMsg().wParam; }
bool WaitObjectContainer::Wait(unsigned long milliseconds) { if (m_noWait || (m_handles.empty() && !m_firstEventTime)) { SetLastResult(LASTRESULT_NOWAIT); return true; } bool timeoutIsScheduledEvent = false; if (m_firstEventTime) { double timeToFirstEvent = SaturatingSubtract(m_firstEventTime, m_eventTimer.ElapsedTimeAsDouble()); if (timeToFirstEvent <= milliseconds) { milliseconds = (unsigned long)timeToFirstEvent; timeoutIsScheduledEvent = true; } if (m_handles.empty() || !milliseconds) { if (milliseconds) Sleep(milliseconds); SetLastResult(timeoutIsScheduledEvent ? LASTRESULT_SCHEDULED : LASTRESULT_TIMEOUT); return timeoutIsScheduledEvent; } } if (m_handles.size() > MAXIMUM_WAIT_OBJECTS) { // too many wait objects for a single WaitForMultipleObjects call, so use multiple threads static const unsigned int WAIT_OBJECTS_PER_THREAD = MAXIMUM_WAIT_OBJECTS-1; unsigned int nThreads = (unsigned int)((m_handles.size() + WAIT_OBJECTS_PER_THREAD - 1) / WAIT_OBJECTS_PER_THREAD); if (nThreads > MAXIMUM_WAIT_OBJECTS) // still too many wait objects, maybe implement recursive threading later? throw Err("WaitObjectContainer: number of wait objects exceeds limit"); CreateThreads(nThreads); DWORD error = S_OK; for (unsigned int i=0; i<m_threads.size(); i++) { WaitingThreadData &thread = *m_threads[i]; while (!thread.waitingToWait) // spin until thread is in the initial "waiting to wait" state Sleep(0); if (i<nThreads) { thread.waitHandles = &m_handles[i*WAIT_OBJECTS_PER_THREAD]; thread.count = UnsignedMin(WAIT_OBJECTS_PER_THREAD, m_handles.size() - i*WAIT_OBJECTS_PER_THREAD); thread.error = &error; } else thread.count = 0; } ResetEvent(m_stopWaiting); PulseEvent(m_startWaiting); DWORD result = ::WaitForSingleObject(m_stopWaiting, milliseconds); if (result == WAIT_OBJECT_0) { if (error == S_OK) return true; else throw Err("WaitObjectContainer: WaitForMultipleObjects in thread failed with error " + IntToString(error)); } SetEvent(m_stopWaiting); if (result == WAIT_TIMEOUT) { SetLastResult(timeoutIsScheduledEvent ? LASTRESULT_SCHEDULED : LASTRESULT_TIMEOUT); return timeoutIsScheduledEvent; } else throw Err("WaitObjectContainer: WaitForSingleObject failed with error " + IntToString(::GetLastError())); } else { #if TRACE_WAIT static Timer t(Timer::MICROSECONDS); static unsigned long lastTime = 0; unsigned long timeBeforeWait = t.ElapsedTime(); #endif DWORD result = ::WaitForMultipleObjects((DWORD)m_handles.size(), &m_handles[0], FALSE, milliseconds); #if TRACE_WAIT if (milliseconds > 0) { unsigned long timeAfterWait = t.ElapsedTime(); OutputDebugString(("Handles " + IntToString(m_handles.size()) + ", Woke up by " + IntToString(result-WAIT_OBJECT_0) + ", Busied for " + IntToString(timeBeforeWait-lastTime) + " us, Waited for " + IntToString(timeAfterWait-timeBeforeWait) + " us, max " + IntToString(milliseconds) + "ms\n").c_str()); lastTime = timeAfterWait; } #endif if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + m_handles.size()) { if (result == m_lastResult) m_sameResultCount++; else { m_lastResult = result; m_sameResultCount = 0; } return true; } else if (result == WAIT_TIMEOUT) { SetLastResult(timeoutIsScheduledEvent ? LASTRESULT_SCHEDULED : LASTRESULT_TIMEOUT); return timeoutIsScheduledEvent; } else throw Err("WaitObjectContainer: WaitForMultipleObjects failed with error " + IntToString(::GetLastError())); } }
static int usb_rtusb_init_device(struct net_device *net_dev) { PRTMP_ADAPTER pAd = (PRTMP_ADAPTER) RTMP_OS_NETDEV_GET_PRIV(net_dev); NDIS_STATUS Status = NDIS_STATUS_SUCCESS; UCHAR TmpPhy; DBGPRINT(RT_DEBUG_TRACE, "%s-->\n", __FUNCTION__); // init mediastate to disconnected OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED); //bottom half data is assign at each task_scheduler tasklet_init(&pAd->rx_bh, RTUSBBulkRxHandle, (unsigned long)pAd); // Initialize pAd->PortCfg to manufacture default PortCfgInit(pAd); // Init RTMP_ADAPTER CmdQElements Status = RTMPInitAdapterBlock(pAd); //always success if (Status != NDIS_STATUS_SUCCESS) { return Status; } // // Init send data structures and related parameters // Status = NICInitTransmit(pAd); //if fail clean itself if (Status != NDIS_STATUS_SUCCESS) { return Status; } // // Init receive data structures and related parameters // Status = NICInitRecv(pAd); if (Status != NDIS_STATUS_SUCCESS) { goto out; } // Wait for hardware stable { ULONG MacCsr0 = 0, Index = 0; do { Status = RTUSBReadMACRegister(pAd, MAC_CSR0, &MacCsr0); if (MacCsr0 != 0) break; RTMPusecDelay(1000); } while (Index++ < 1000); DBGPRINT(RT_DEBUG_TRACE, "Init: MAC_CSR0=0x%08x, Status=0x%08x\n", MacCsr0, Status); } // Load 8051 firmware Status = NICLoadFirmware(pAd); if(Status != NDIS_STATUS_SUCCESS) { goto out; } // Initialize Asics NICInitializeAsic(pAd); #ifdef BLOCK_NET_IF initblockQueueTab(pAd); #endif // BLOCK_NET_IF // // Read RaConfig profile parameters #ifdef READ_PROFILE_FROM_FILE RTMPReadParametersFromFile(pAd); #endif // // Read additional info from NIC such as MAC address // This function must called after register CSR base address // #ifdef INIT_FROM_EEPROM NICReadEEPROMParameters(pAd); NICInitAsicFromEEPROM(pAd); #endif RTUSBWriteHWMACAddress(pAd); // external LNA has different R17 base if (pAd->NicConfig2.field.ExternalLNA) { pAd->BbpTuning.R17LowerBoundA += 0x10; pAd->BbpTuning.R17UpperBoundA += 0x10; pAd->BbpTuning.R17LowerBoundG += 0x10; pAd->BbpTuning.R17UpperBoundG += 0x10; } // hardware initialization after all parameters are acquired from // Registry or E2PROM TmpPhy = pAd->PortCfg.PhyMode; pAd->PortCfg.PhyMode = 0xff; RTMPSetPhyMode(pAd, TmpPhy); // max desired rate might be reset as call phymode setup, so set TxRate again if (pAd->PortCfg.DefaultMaxDesiredRate == 0) RTMPSetDesiredRates(pAd, -1); else RTMPSetDesiredRates(pAd, (LONG) (RateIdToMbps[pAd->PortCfg.DefaultMaxDesiredRate - 1] * 1000000)); // // initialize MLME // Status = MlmeInit(pAd); if(Status != NDIS_STATUS_SUCCESS) { goto out; } // mlmethread & RTUSBCmd flag restart mlme_kill = 0; RTUSBCmd_kill =0; CreateThreads(net_dev); // at every open handler, copy mac address. COPY_MAC_ADDR(pAd->net_dev->dev_addr, pAd->CurrentAddress); // USB_ID info for UI pAd->VendorDesc = 0x148F2573; DBGPRINT(RT_DEBUG_TRACE, "%s<--\n", __FUNCTION__); return 0; out: ReleaseAdapter(pAd, TRUE, FALSE); return Status; }
int main(int argc, char **argv) #endif { PLOptStatus os; PRIntn duration = DEFAULT_DURATION; PRUint32 totalCount, highCount = 0, lowCount = 0; PLOptState *opt = PL_CreateOptState(argc, argv, "hdc:"); debug_out = PR_STDOUT; oneSecond = PR_SecondsToInterval(1); while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) { if (PL_OPT_BAD == os) continue; switch (opt->option) { case 'd': /* debug mode */ debug_mode = PR_TRUE; break; case 'c': /* test duration */ duration = atoi(opt->value); break; case 'h': /* help message */ default: Help(); return 2; } } PL_DestroyOptState(opt); PR_STDIO_INIT(); if (duration == 0) duration = DEFAULT_DURATION; RudimentaryTests(); printf("Priority test: running for %d seconds\n\n", duration); (void)PerSecond(PR_IntervalNow()); totalCount = PerSecond(PR_IntervalNow()); PR_SetThreadPriority(PR_GetCurrentThread(), PR_PRIORITY_URGENT); if (debug_mode) { PR_fprintf(debug_out, "The high priority thread should get approximately three\n"); PR_fprintf( debug_out, "times what the low priority thread manages. A maximum of \n"); PR_fprintf( debug_out, "%d cycles are available.\n\n", totalCount); } duration = (duration + 4) / 5; CreateThreads(&lowCount, &highCount); while (duration--) { PRIntn loop = 5; while (loop--) PR_Sleep(oneSecond); if (debug_mode) PR_fprintf(debug_out, "high : low :: %d : %d\n", highCount, lowCount); } PR_ProcessExit((failed) ? 1 : 0); PR_NOT_REACHED("You can't get here -- but you did!"); return 1; /* or here */ } /* main */