void AppInit(void) { TouchPanelTask.Run(); GUITask.Run(); BlinkTask.Run(); printf("Gib was ein:\r\n"); Serial.ReadLn(buf, 10); printf("Du hast eingegeben: %s", buf); }
/** * @brief ThreadPool::worker - get next task from queue and run it. */ void ThreadPool::worker() { Task* task = nullptr; while (m_needStop == false) { while (empty()) { unique_lock<mutex> lock(m_mutex); m_condVar.wait_for(lock, chrono::seconds(60)); if (m_needStop) { unique_lock<mutex> lockPrint(m_mutexPrint); cout << "Thread #" << this_thread::get_id() << " has finished work" << endl; return; } } task = getTask(); if (task != nullptr) { { unique_lock<mutex> lockPrint(m_mutexPrint); cout << "[" << this_thread::get_id() << "] " << "Task priority: " << task->getPriority() << " Task result: "; } task->Run(); } this_thread::yield(); this_thread::sleep_for(chrono::milliseconds(genRand())); } }
static void ThreadFunction(ThreadFunctionArg input){ Thread::Thread_Impl &thimble = input.first; // Call monitor.NotifyAll() until stated equals true to ensure the thread has started. thimble.monitor.UnboundWait(); input.second = true; Task *task; while(thimble.live){ if(thimble.queue.try_pop(task)){ task->Run(); if(task->repeating) thimble.queue.push(task); else delete task; } thimble.monitor.UnboundWait(); } }
void* LinuxThread::_ThreadProc(void* ptrVoid) { LinuxThread* ptrThis = (LinuxThread*)ptrVoid; LinuxThreadPool* pool; Task* task; pool = dynamic_cast<LinuxThreadPool*>(ptrThis->GetThreadPool()); if (pool == NULL) return (void*)ER; while (1) { if(ptrThis->_shouldTerminate()) break; task = pool->GetTask(); if (task) { task->Run(); delete task; task = NULL; } else { ptrThis->_suspend(); } } return (void*)OK; }
void TaskScheduler::WaitForTaskFinished(TaskId const & parTaskId) { while (IsTaskFinished(parTaskId)) { // don't waste my time, maybe I can work with you my friends Task * task = nullptr; if (_useThisThreadDuringWait) { std::lock_guard<std::mutex> ul(this->_taskListMutex); task = PickupTaskIFP(); } if (task) { task->Run(); ReleaseTask(task); task = nullptr; } else { std::unique_lock<std::mutex> ul(this->_taskListMutex); this->_oneTaskRelease.wait(ul); } } }
void Scheduler::ThreadLoop() { for(;;) { Task todo; { std::unique_lock<std::mutex> lock(mutex); if (!go_on) // must test it while locked break; if (tasks.empty()) { blocker.wait(lock); continue; } if (tasks.begin()->first <= std::chrono::system_clock::now()) { todo = tasks.begin()->second; tasks.erase(tasks.begin()); } else { blocker.wait_until(lock, tasks.begin()->first); continue; } } // Run task while unlocked so it can schedule new tasks todo.Run(); } }
void RepetitiveTask(Task::TaskData & parTask) { TaskScheduler * scheduler = parTask.RepetetiveTaskData.Scheduler; TaskId taskToExec = parTask.RepetetiveTaskData.RepetiveTask; std::chrono::milliseconds repeatTimer = parTask.RepetetiveTaskData.RepeatTimer; Task * task = scheduler->GetTask(taskToExec); assert(task != nullptr); task->Run(); scheduler->ScheduleEvery(repeatTimer, taskToExec, false); }
unsigned int __stdcall RenderWorkThread(LPVOID param) { RenderThreadParam *p = (RenderThreadParam *) param; Task *task = NULL; while ( true ) { task = gEngine.taskManager.ExtractTask(); if ( !task ) break; task->Run(); delete task; } return 0; }
void Thread::PerformTask(TaskGroup *pool){ while(true){ Task * task; if(!pool->queue.try_pop(task)) break; task->Run(); if(task->repeating) pool->queue.push(task); else delete task; } }
static DWORD WINAPI taskEntry(LPVOID arg) { #else static void *taskEntry(void *arg) { #endif while (true) { workerSemaphore.Wait(); // Try to get task from task queue Task *myTask = NULL; { MutexLock lock(*taskQueueMutex); if (taskQueue.size() == 0) break; myTask = taskQueue.back(); taskQueue.pop_back(); } // Do work for _myTask_ PBRT_STARTED_TASK(myTask); myTask->Run(); PBRT_FINISHED_TASK(myTask); tasksRunningCondition.Lock(); int unfinished = --numUnfinishedTasks; if (unfinished == 0) tasksRunningCondition.Signal(); tasksRunningCondition.Unlock(); } // Cleanup from task thread and exit #ifdef PBRT_HAS_PTHREADS pthread_exit(NULL); #endif // PBRT_HAS_PTHREADS return 0; } #endif // !PBRT_USE_GRAND_CENTRAL_DISPATCH void WaitForAllTasks() { #ifdef PBRT_USE_GRAND_CENTRAL_DISPATCH dispatch_group_wait(gcdGroup, DISPATCH_TIME_FOREVER); #else tasksRunningCondition.Lock(); while (numUnfinishedTasks > 0) tasksRunningCondition.Wait(); tasksRunningCondition.Unlock(); #endif }
void Farm::WorkerFunction() { while (true) { queueLock_.lock(); Task *t = NULL; if (!tasks_.empty()) { t = tasks_.front(); tasks_.pop(); } queueLock_.unlock(); if (t == NULL) { break; } else { t->Run(); } } //another suggestion psudeoish code //Task *t = nullptr; //do { // { // lock_guard<mutex> lock(queueLock); // if (!queue.empty()) // t = queue.pop(); // } // if (t != nullptr) // t->run(); //} while (t != nullptr); }
void Worker::Loop() { if (terminate_requested_) { return; } Task* t = queue_->GetNext(); if (!t) { //printf("%08x: no task\n", ::GetCurrentThreadId()); ::SleepEx(1, TRUE); return; } t->Run(); SleepEx(0, TRUE); // handle completion routines }
inline void TaskThread::Run(void* arg) { idleStart = time(NULL); do { currentTask = queue.Pop(); if (currentTask != NULL) { currentTask->Run(); currentTask = NULL; idleStart = time(NULL); } else { Sleep(1); } } while (!GetStop()); }
unsigned __stdcall TaskQueue::Thread(void *argList) { DWORD threadID = GetCurrentThreadId(); Task * task; TaskQueue * taskQueue = (TaskQueue *)argList; while(1) { taskQueue->logger->Log(LOG_DEFAULT, L"Thread[%d] Before GetTask().\n", threadID); task = taskQueue->GetTask(); taskQueue->logger->Log(LOG_DEFAULT, L"Thread[%d] After GetTask().\n", threadID); if (task) { task->Run(); taskQueue->logger->Log(LOG_DEFAULT, L"Thread[%d] Task complete.\n", threadID); } else break; } taskQueue->logger->Log(LOG_DEFAULT, L"Thread[%d] Before exit.\n", threadID); return 0; }
void Run(Task<void()>& task) { m_voidGroup.push_back(task.Run()); }
void Run(Task<R()>& task) { m_group.insert(std::make_pair<RetVariant, Any>(R(), task.Run())); }
void TaskThread::Entry() { Task* theTask = NULL; while (true) { theTask = this->WaitForTask(); // // WaitForTask returns NULL when it is time to quit if (theTask == NULL || false == theTask->Valid()) return; Bool16 doneProcessingEvent = false; while (!doneProcessingEvent) { //If a task holds locks when it returns from its Run function, //that would be catastrophic and certainly lead to a deadlock #if DEBUG Assert(this->GetNumLocksHeld() == 0); Assert(theTask->fInRunCount == 0); theTask->fInRunCount++; #endif theTask->fUseThisThread = NULL; // Each invocation of Run must independently // request a specific thread. SInt64 theTimeout = 0; if (theTask->fWriteLock) { OSMutexWriteLocker mutexLocker(&TaskThreadPool::sMutexRW); if (TASK_DEBUG) qtss_printf("TaskThread::Entry run global locked TaskName=%s CurMSec=%.3f thread=%p task=%p\n", theTask->fTaskName, OS::StartTimeMilli_Float(), (void *) this, (void *)theTask); theTimeout = theTask->Run(); theTask->fWriteLock = false; } else { OSMutexReadLocker mutexLocker(&TaskThreadPool::sMutexRW); if (TASK_DEBUG) qtss_printf("TaskThread::Entry run TaskName=%s CurMSec=%.3f thread=%p task=%p\n", theTask->fTaskName, OS::StartTimeMilli_Float(), (void *) this, (void *)theTask); theTimeout = theTask->Run(); } #if DEBUG Assert(this->GetNumLocksHeld() == 0); theTask->fInRunCount--; Assert(theTask->fInRunCount == 0); #endif if (theTimeout < 0) { if (TASK_DEBUG) { qtss_printf("TaskThread::Entry delete TaskName=%s CurMSec=%.3f thread=%p task=%p\n", theTask->fTaskName, OS::StartTimeMilli_Float(), (void *) this, (void *)theTask); theTask->fUseThisThread = NULL; if (NULL != fHeap.Remove(&theTask->fTimerHeapElem)) qtss_printf("TaskThread::Entry task still in heap before delete\n"); if (NULL != theTask->fTaskQueueElem.InQueue()) qtss_printf("TaskThread::Entry task still in queue before delete\n"); theTask->fTaskQueueElem.Remove(); if (theTask->fEvents &~Task::kAlive) qtss_printf("TaskThread::Entry flags still set before delete\n"); (void)atomic_sub(&theTask->fEvents, 0); ::strncat(theTask->fTaskName, " deleted", sizeof(theTask->fTaskName) - 1); } theTask->fTaskName[0] = 'D'; //mark as dead delete theTask; theTask = NULL; doneProcessingEvent = true; } else if (theTimeout == 0) { //We want to make sure that 100% definitely the task's Run function WILL //be invoked when another thread calls Signal. We also want to make sure //that if an event sneaks in right as the task is returning from Run() //(via Signal) that the Run function will be invoked again. doneProcessingEvent = compare_and_store(Task::kAlive, 0, &theTask->fEvents); if (doneProcessingEvent) theTask = NULL; } else { //note that if we get here, we don't reset theTask, so it will get passed into //WaitForTask if (TASK_DEBUG) qtss_printf("TaskThread::Entry insert TaskName=%s in timer heap thread=%p elem=%p task=%p timeout=%.2f\n", theTask->fTaskName, (void *) this, (void *)&theTask->fTimerHeapElem, (void *)theTask, (float)theTimeout / (float)1000); theTask->fTimerHeapElem.SetValue(OS::Milliseconds() + theTimeout); fHeap.Insert(&theTask->fTimerHeapElem); (void)atomic_or(&theTask->fEvents, Task::kIdleEvent); doneProcessingEvent = true; } #if TASK_DEBUG SInt64 yieldStart = OS::Milliseconds(); #endif this->ThreadYield(); #if TASK_DEBUG SInt64 yieldDur = OS::Milliseconds() - yieldStart; static SInt64 numZeroYields; if (yieldDur > 1) { if (TASK_DEBUG) qtss_printf("TaskThread::Entry time in Yield %qd, numZeroYields %qd \n", yieldDur, numZeroYields); numZeroYields = 0; } else numZeroYields++; #endif } } }
int main(int argc, char* argv[]) { // DAEMON_FLAG: 守护进程标志位('1'-有效) // LOG_ID :日志 ID // MODE : 模式 // CFG_FILE :配置文件 if ( argc != 5 ) { std::cerr << "[usage]" << argv[0] << " DAEMON_FLAG LOG_ID MODE CFG_FILE" << std::endl; return -1; } // Daemon process ? bool is_daemon = (strcmp(argv[1], "1") == 0); if ( is_daemon ) { pid_t f_pid = fork(); if ( f_pid < 0 ) // fork error ! { std::cerr << "Process fork error: " << f_pid << std::endl; return -1; } else if ( f_pid > 0 ) // Parent process end ! { std::cout << "[DAEMON] Parent process [pid=" << getpid() << "] end" << std::endl; std::cout << "[DAEMON] Child process [pid=" << f_pid << "] start" << std::endl; return 0; } } // 日志配置 long long log_id = 0; if ( !base::PubStr::Str2LLong(argv[2], log_id) ) { std::cerr << "[ERROR] Unknown log ID: '" << argv[2] << "'" << std::endl; return -1; } base::LogStrategy log_strategy; log_strategy.log_id = log_id; base::AutoLogger aLog; base::Log* pLog = aLog.Get(); try { // 读取配置 base::Config cfg; cfg.SetCfgFile(argv[4]); cfg.RegisterItem("LOG", "PATH"); cfg.RegisterItem("LOG", "MAX_LINE"); cfg.RegisterItem("LOG", "MAX_SIZE"); cfg.RegisterItem("LOG", "INTERVAL"); cfg.ReadConfig(); log_strategy.log_path = cfg.GetCfgValue("LOG", "PATH"); log_strategy.max_line = cfg.GetCfgLongVal("LOG", "MAX_LINE"); log_strategy.max_size = cfg.GetCfgLongVal("LOG", "MAX_SIZE"); log_strategy.interval = cfg.GetCfgValue("LOG", "INTERVAL"); TaskFactory t_factory(cfg); std::string str_tmp; Task* pTask = t_factory.Create(argv[3], &str_tmp); if ( NULL == pTask ) { std::cerr << "[ERROR] Create task failed: " << str_tmp << std::endl; return -1; } base::PubStr::SetFormatString(str_tmp, "%s: PID=[%d]", (is_daemon?"守护进程":"一般进程"), getpid()); log_strategy.log_headers.push_back(str_tmp); log_strategy.log_headers.push_back(pTask->Version()); log_strategy.log_prefix = pTask->LogPrefix(); pLog->Init(log_strategy); std::cout << pTask->Version() << std::endl; pTask->Run(); } catch ( base::Exception& ex ) { std::cerr << "[ERROR] " << ex.What() << ", ERROR_CODE: " << ex.ErrorCode() << std::endl; pLog->Output("[ERROR] %s, ERROR_CODE: %d", ex.What().c_str(), ex.ErrorCode()); return -2; } catch ( ... ) { std::cerr << "[ERROR] Unknown error! [FILE:" << __FILE__ << ", LINE:" << __LINE__ << "]" << std::endl; pLog->Output("[ERROR] Unknown error! [FILE:%s, LINE:%d]", __FILE__, __LINE__); return -3; } std::cout << argv[0] << " quit !" << std::endl; pLog->Output("%s quit !", argv[0]); return 0; }
static void lRunTask(void *t) { Task *task = (Task *)t; PBRT_STARTED_TASK(task); task->Run(); PBRT_FINISHED_TASK(task); }