bool Worker::addProcessor(int id, Runnable *processor)
{
    bool ret = false;
    std::map<int, Runnable*> runnables;
    Runnable* current;

    std::lock_guard<std::mutex> guard(mtx);

    while (!processors.empty()){
        current = processors.top();
        processors.pop();
        runnables[current->getId()] = current;
    }

    if (runnables.count(id) == 0) {
        processor->setId(id);
        runnables[id] = processor;
        ret = true;
    }

    for (auto it : runnables){
        processors.push(it.second);
    }

    return ret;
}
bool Worker::removeProcessor(int id)
{
    bool ret = false;
    std::map<int, Runnable*> runnables;
    Runnable* current;

    std::lock_guard<std::mutex> guard(mtx);

    while (!processors.empty()){
        current = processors.top();
        processors.pop();
        runnables[current->getId()] = current;
    }

    while (runnables.count(id) > 0) {
        runnables.erase(id);
        ret = true;
    }

    for (auto it : runnables){
        processors.push(it.second);
    }

    return ret;
}
	static void* execute_thread(void * ptr)
	{
		Runnable* runnable = static_cast<Runnable*>(ptr);
		assert(runnable);
		runnable->run();
		pthread_exit(NULL);
	}
Exemple #4
0
 void AsyncTaskExecutor::run()
 {
     while(_isRunning)
     {
         std::unique_lock<std::mutex> lock(_mutex);
         if(!_queue.empty())
         {
             Runnable *task = _queue.front();
             _queue.pop_front();
             if(task!=NULL)
             {
                 _isBusy = true;
                 _currentTask = task;
                 lock.unlock();
                 task->run();
                 lock.lock();
                 _currentTask = NULL;
                 if(task->toDelete())
                     delete task;
             }
         }
         else if(_isRunning)
         {
             _isBusy = false;
             _signal.wait(lock);
         }
     }
     return;
 }
//TODO: avoid void functions
void Worker::getState(Jzon::Object &workerNode)
{
    Jzon::Array pList;
    std::map<int, Runnable*> runnables;
    Runnable* current;

    {
        std::lock_guard<std::mutex> guard(mtx);

        while (!processors.empty()){
            current = processors.top();
            processors.pop();
            runnables[current->getId()] = current;
        }

        for (auto it : runnables){
            processors.push(it.second);
        }

    }

    for (auto it : runnables) {
        pList.Add(it.first);
    }

    workerNode.Add("type", utils::getWorkerTypeAsString(type));
    workerNode.Add("processors", pList);
}
Exemple #6
0
Milliseconds RunLoop::Impl::processRunnables() {
    std::lock_guard<std::recursive_mutex> lock(mtx);

    auto now = Clock::now();
    auto nextDue = TimePoint::max();

    // O(N) but in the render thread where we get tons
    // of messages, the size of the list is usually 1~2.
    for (nextRunnable = runnables.begin(); nextRunnable != runnables.end();) {
        Runnable* runnable = *(nextRunnable++);

        auto const dueTime = runnable->dueTime();
        if (dueTime <= now) {
            runnable->runTask();
        } else {
            nextDue = std::min(nextDue, dueTime);
        }
    }

    if (runnables.empty() || nextDue == TimePoint::max()) {
        return Milliseconds(-1);
    }

    auto timeout = std::chrono::duration_cast<Milliseconds>(nextDue - now);
    if (alarm) {
        alarm->invoke(&Alarm::set, timeout);
    }

    return timeout;
}
Exemple #7
0
void
RunnableHandler::handleEvent( void * e)
{
    Runnable *r = reinterpret_cast< Runnable * > (e);
    r->run();
    if( d_->del_ )
    {
        delete r;
    }
}
Exemple #8
0
void *Thread_Unix::thread_main(void *data)
{
	// kill thread immediately - no cancellation point
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr);

	Runnable *runnable = (Runnable *)data;
	ThreadLocalStorage tls;
	runnable->run();
	return nullptr;
}
Exemple #9
0
 void TaskExecutor::clearAll()
 {
     std::lock_guard<std::mutex> lock(_mutex);
     for(int i = 0; i < _queue.size(); i++)
     {
         Runnable *task = _queue[i];
         if(task && task->toDelete())
             delete task;
     }
     _queue.clear();
 }
Exemple #10
0
	virtual void handleMessage(const Message& message) {
		switch (message.what) {
		case 4:
		case 5: {
			Runnable* runnable = (Runnable*) message.obj;
			runnable->run();
			break;
		}
		default:
			Log::i(LOG_TAG, "Handler1::handleMessage 0x%x with ID %d by Looper 0x%x", &message, message.what, Looper::myLooper());
		}
	}
Exemple #11
0
void test_suite::func_begin(const std::string & name)
{
	// Run test initializers
	const_it it = test_vec.find(name);
	if(it!=test_vec.end())
	{
		(*it).second->begin();
		return;
	}
	Runnable *pTest = new Runnable(name);
	test_vec.insert(pair<string,Runnable*>(name,pTest));
	none_init_vec.push_back(pTest);
	pTest->begin();
}
Exemple #12
0
void ThreadQueue::onStarted()
{
    Runnable* r;

    // qDebug() << "has started";

    while ((r = hasMore()) != NULL)
    {
        //qDebug() << "executing next from list" << r->name();
        QVariant result = r->run();
        emit     finished(r, result);
    }
    thread()->quit();
}
/**
执行任务的工作线程。
当前没有任务时,
如果当前线程数量大于最小线程数量,减少线程,
否则,执行清理程序,将线程类给释放掉
**/
void CThreadPoolExecutor::CWorker::Run()
{
	Runnable * pTask = NULL;
	while (m_bRun)
	{
		if (NULL == m_pFirstTask)
		{
			pTask = m_pThreadPool->GetTask();
		}
		else
		{
			pTask = m_pFirstTask;
			m_pFirstTask = NULL;
		}

		if (NULL == pTask)
		{
			EnterCriticalSection(&(m_pThreadPool->m_csThreadPoolLock));
			if (m_pThreadPool->GetThreadPoolSize() > m_pThreadPool->m_minThreads)
			{
				ThreadPoolItr itr = m_pThreadPool->m_ThreadPool.find(this);
				if (itr != m_pThreadPool->m_ThreadPool.end())
				{
					m_pThreadPool->m_ThreadPool.erase(itr);
					m_pThreadPool->m_TrashThread.insert(this);
				}
				m_bRun = false;
			}
			else
			{
				ThreadPoolItr itr = m_pThreadPool->m_TrashThread.begin();
				while (itr != m_pThreadPool->m_TrashThread.end())
				{
					(*itr)->Join();
					delete (*itr);
					m_pThreadPool->m_TrashThread.erase(itr);
					itr = m_pThreadPool->m_TrashThread.begin();
				}
			}
			LeaveCriticalSection(&(m_pThreadPool->m_csThreadPoolLock));
			continue;
		}
		else
		{
			pTask->Run();
			pTask = NULL;
		}
	}
}
Exemple #14
0
void ChannelService::OnSoftSignal(uint32 soft_signo, uint32 appendinfo)
{
    switch (soft_signo)
    {
        case CHANNEL_REMOVE:
        {
            //uint32 chanel_id = appendinfo;
            VerifyRemoveQueue();
            break;
        }
        case WAKEUP:
        {
            Runnable* task = NULL;
            while (m_pending_tasks.Pop(task))
            {
                if (NULL != task)
                {
                    task->Run();
                }
            }
            break;
        }
        case USER_DEFINED:
        {
            if (NULL != m_user_cb)
            {
                m_user_cb(this, appendinfo, m_user_cb_data);
            }
            break;
        }
        case CHANNEL_ASNC_IO:
        {
            ChannelAsyncIOContext ctx;
            while (m_async_io_queue.Pop(ctx))
            {
                if (NULL != ctx.cb)
                {
                    Channel* ch = GetChannel(ctx.channel_id);
                    ctx.cb(ch, ctx.data);
                }
            }
            break;
        }
        default:
        {
            break;
        }
    }
}
Exemple #15
0
 void TaskExecutor::executeAll()
 {
     std::lock_guard<std::mutex> lock(_mutex);
     while(!_queue.empty())
     {
         Runnable *task = _queue.front();
         _queue.pop_front();
         if(task!=NULL)
         {
             task->run();
             if(task->toDelete())
                 delete task;
         }
     }
 }
Exemple #16
0
 const SUCCESS loop() override
 {
     stringstream ss;
     switch(counter)
     {
     case NAME:
         ss<<"Window is titled "<<win->getName();
         counter = POSITION;
         break;
     case POSITION:
         (ss<<"Window is at position ")<<win->getPosition();
         counter = SIZE;
         break;
     case SIZE:
         ss<<"Window has dimensions "<<win->getSize();
         counter = ID;
         break;
     case ID:
         ss<<"Window has ID "<<int(win->getID());
         counter = STAHP;
         break;
     case STAHP:
         runner->stop();
         break;
     default:
         return FAILED;
     }
     query = ss.str();
     SDL_Delay(delay);
     return SUCCEEDED;
 }
            LRESULT OnTaskHandleMsg(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
            {
                Runnable* pRunnable = (Runnable *)wParam;

                if (pRunnable)
                {
                    pRunnable->Run();

                    if (pRunnable->IsBeHosted())
                    {
                        pRunnable->Release();
                    }
                }

                return 0;
            }
            /**
             * This method encapsulates the runnable.
             */
            void *threadRunner(void *v) {
                pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
                Runnable *runnable = static_cast<Runnable*>(v);

                try {
                    runnable->run();
                } catch (string &s) {
                    clog << "Exception caught at " << __FILE__ << ":" << __LINE__ << ": " << s << endl;
                    throw;
                } catch (...) {
                    clog << "Unknown exception caught at " << __FILE__ << ":" << __LINE__ << "." << endl;
                    throw;
                }

                return NULL;
            }
void Widget::on_pushButton_clicked()
{
    QList<QStandardItem *> row;
    QString taskName = QString("Task %1").arg(m_model->rowCount());
    row << new QStandardItem(taskName) << new QStandardItem("queued");
    m_model->appendRow(row);

    Runnable *runnable = new Runnable(taskName, this);
    runnable->setAutoDelete(true);
    QThreadPool::globalInstance()->start(runnable);

    if (m_model->rowCount() < 2) {
        int width(ui->tableView->contentsRect().width() - ui->tableView->verticalScrollBar()->width());
        ui->tableView->setColumnWidth(0, width / 2);
        ui->tableView->setColumnWidth(1, width / 2);

    }
}
Exemple #20
0
                void threadLogic()
                {
                    try
                    {
                        while(!STOP_FLAG)
                        {
                            Runnable *runnable = workQueue.pull();

                            if(runnable != NULL)
                            {
                                runnable->run();
                                delete runnable;
                            }
                        }
                    }
                    catch(const boost::thread_interrupted&)
                    { }
                }; 
Exemple #21
0
	/**
	 * システムコールバック用エントリポイント
	 * Mutex作成後にConstructorのcreateOnRunフラグ動作用のMutexを追加して
	 * この関数内の頭に仕込んでおく必要があるな・・・
	 */
	static void* CallbackDispatcher(void* DispatchKey)
	{
		PosixThread* This = reinterpret_cast<PosixThread*>(DispatchKey);
		assert(dynamic_cast<PosixThread*>(This) != NULL);

		// wait for start signal.
		ScopedLock<PosixMutex> lock(This->starter);

		int retValue = 0;

		{
			ScopedLock<PosixMutex> lock(This->statusSync);
			This->isRun = true;
		}

		try 
		{
			Runnable* entry = This->getRunningTarget();
			entry->prepare();
			retValue = entry->run();
			entry->dispose();
		}
		catch (ThreadException& e)
		{
			This->transporter = new ThreadException(e);
			retValue = abort_by_exception;
		}
		catch (...)
		{
			This->transporter =	new ThreadException("unknown exception.");
			retValue = abort_by_exception;
		}

		{
			ScopedLock<PosixMutex> lock(This->statusSync);
			This->isRun = false;
		}

		pthread_exit(reinterpret_cast<void*>(retValue));

		return 0;
	}
void Worker::process()
{
    Runnable* currentJob = NULL;
    
    std::unique_lock<std::mutex> guard(mtx);
    while(run && !processors.empty()) { 
        currentJob = processors.top();
        processors.pop();
        
        guard.unlock();
        
        currentJob->sleepUntilReady();
        currentJob->runProcessFrame();
            
        guard.lock();
        
        processors.push(currentJob);
    }
   
    thread.detach();
}
Exemple #23
0
    Thread::Thread(Runnable &runnable, bool detached) :
        runnable_(&runnable),
#ifndef _WIN32
        thread_(0),
#endif
        joined_(false), detached_(detached) {
        LOG_DEBUG("Thread::Thread("<< &runnable <<":"<< runnable.getName() <<")");
        pthread_attr_init(&attr_);
        if (detached) {
            pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED);
        }
    }
Exemple #24
0
 void
 Thread::Run::exec(void) {
   while (true) {
     // Execute runnable
     {
       Runnable* e;
       m.acquire();
       e=r; r=NULL;
       m.release();
       assert(e != NULL);
       e->run();
       delete e;
     }
     // Put into idle stack
     Thread::m()->acquire();
     n=Thread::idle; Thread::idle=this;
     Thread::m()->release();
     // Wait for next runnable
     e.wait();
   }
 }
Exemple #25
0
void ThreadPoolImpl::Destroy()
{
	if (!m_bCreate) {
		return;
	}

	do
	{
		//!should wait dead thread have been deleted.
		unsigned int nThread = 0, nTask = 0;
		this->Statistic(nThread, nTask);
		if (m_nMinThread == nThread && 0 == nTask) {
			break;
		}
		else {
			Thread::Sleep(10);
		}

	} while (1);

	TAutoLock lock(m_mtxThread);
	ThreadIterator itr = m_threads.begin();
	while (itr != m_threads.end())
	{
		//!should wait all thread have been done.
		Thread   *pThread = (*itr);
		Runnable *pWorker = pThread->GetRunnable();
		pWorker->Stop();
		pThread->Join();
		delete pThread;
		(*itr) = 0;
		m_threads.erase(itr);
		itr = m_threads.begin();
	}

	//!now, there should be no task.
	assert(m_tasks.empty());
	m_bCreate = false;
}
Exemple #26
0
    void run()
    {
        while (true)
        {

            if (mRequest->isEmpty())
            {
                cout << "exiting run()" << endl;
                return;
            }

            // Pull a runnable off the queue
            Runnable *handler;
            mRequest->dequeue(handler);

            // Run the runnable that we pulled off the queue
            handler->run();

            // Delete the runnable we pulled off the queue
            delete handler;

        }
    }
Exemple #27
0
VOID Thread::__thr_run (VOID * arg)
{
  // Get the thread object, and update its remaining attributes.
  Thread * thr = reinterpret_cast <Thread *> (arg);
  
  // Set the current thread to the Thread object. This allows the
  // client to access the Thread object via the current () method.
  Thread::current_.set (thr->thr_id_, thr);
  
  do
  {
    Write_Guard <RW_Mutex> guard (thr->rw_mutex_);
    thr->os_thr_id_ = PIN_GetTid ();
    thr->parent_os_thr_id_ = PIN_GetParentTid ();
    
    // Set the state to running.
    thr->state_ = RUNNING;
  } while (0);

  // Determine what run method we should invoke. Either we invoke the run()
  // method on the runnable_ object contained in the thread, or we invoke
  // the run() method on the thread. The runnable_ variable takes precedence
  // over the run() method on the Thread.
  Runnable * runnable = thr->runnable_;

  if (0 == runnable)
    runnable = thr;

  runnable->run ();

  do
  {
    // Reset the thread state.
    Write_Guard <RW_Mutex> guard (thr->rw_mutex_);
    thr->state_ = TERMINATED;
  } while (0);
}
Exemple #28
0
void LinkageWorker::OnCommand()
{
    std::list<Runnable *> q;
    MutexLocker locker(_mutex);
    q.swap(_commands);
    locker.Unlock();

    for (std::list<Runnable *>::iterator p = q.begin(); p != q.end(); ++p) {
        Runnable *command = *p;
        if (!command) {
            ev_break(_loop, EVBREAK_ALL);
            _quit = true;
            return;
        }

        if (!command->Run()) {
            break;
        }
    }

    for (std::list<Runnable *>::iterator p = q.begin(); p != q.end(); ++p) {
        delete *p;
    }
}
Exemple #29
0
 const SUCCESS loop() override
 {
     SDL_SetRenderDrawColor(ren->getRenderer(), 255, 0, 0, 0);
     SUCCESS ret = SUCCEEDED;
     for(auto i = points.begin(); i != current; i++)
     {
         ret |= SDL_RenderDrawLine(ren->getRenderer(), i->x(), i->y(), (i+1)->x(), (i+1)->y());
     }
     
     if(++current == points.end())
         ender->stop();
     
     SDL_SetRenderDrawColor(ren->getRenderer(), 0, 0, 0, 0);
     
     return ret;
 }
Exemple #30
0
void PooledThread::run()
{
	_started.set();
	for (;;)
	{
		_targetReady.wait();
		_mutex.lock();
		if (_pTarget) // a NULL target means kill yourself
		{
			_mutex.unlock();
			try
			{
				_pTarget->run();
			}
			catch (Exception& exc)
			{
				ErrorHandler::handle(exc);
			}
			catch (std::exception& exc)
			{
				ErrorHandler::handle(exc);
			}
			catch (...)
			{
				ErrorHandler::handle();
			}
			FastMutex::ScopedLock lock(_mutex);
			_pTarget  = 0;
#if defined(_WIN32_WCE) && _WIN32_WCE < 0x800
			_idleTime = wceex_time(NULL);
#else
			_idleTime = time(NULL);
#endif	
			_idle     = true;
			_targetCompleted.set();
			ThreadLocalStorage::clear();
			_thread.setName(_name);
			_thread.setPriority(Thread::PRIO_NORMAL);
		}
		else
		{
			_mutex.unlock();
			break;
		}
	}
}