void ThreadPool::setConcurrentJobs(int concurrentJobs) { if (concurrentJobs == mConcurrentJobs) return; if (concurrentJobs > mConcurrentJobs) { std::lock_guard<std::mutex> lock(mMutex); for (int i = mConcurrentJobs; i < concurrentJobs; ++i) { mThreads.push_back(new ThreadPoolThread(this)); mThreads.back()->start(mPriority, mThreadStackSize); } mConcurrentJobs = concurrentJobs; } else { std::unique_lock<std::mutex> lock(mMutex); for (int i = mConcurrentJobs; i > concurrentJobs; --i) { ThreadPoolThread* t = mThreads.back(); mThreads.pop_back(); lock.unlock(); t->stop(); t->join(); lock.lock(); delete t; } mConcurrentJobs = concurrentJobs; } }
QThreadPoolThread* ThreadPool::createThreadPoolThread() const { ThreadPoolThread* ret = new ThreadPoolThread(); ret->setObjectName(QLatin1String("Global Thread (Pooled)")); return ret; }
void ThreadPool::run() { for (uint8 x=0; x<m_uiCount; x++) { ThreadPoolThread *thread = new ThreadPoolThread(this, false); thread->onCompleteEvent += delegate(this, &ThreadPool::onThreadComplete); m_vThreadList.push_back( thread ); thread->start(); } while (!isStopped()) { doPause(); removedForced(); uint32 runTaskCount = activeThreads(); if (runTaskCount < m_uiCount) startNewTasks(); runTaskCount = activeThreads(); if ((runTaskCount == m_uiCount || m_vTaskList.empty()) && !isStopped()) m_WaitCondition.wait(); } }
QThreadPoolThread* ThreadPool::createThreadPoolThread() const { ThreadPoolThread* ret = new ThreadPoolThread(); ret->setThreadName("Global Thread (Pooled)"); return ret; }
ThreadPool::~ThreadPool() { if (sInstance == this) sInstance = 0; std::unique_lock<std::mutex> lock(mMutex); mJobs.clear(); lock.unlock(); for (List<ThreadPoolThread*>::iterator it = mThreads.begin(); it != mThreads.end(); ++it) { ThreadPoolThread* t = *it; t->stop(); t->join(); delete t; } }
void ThreadPool::forceTask(BaseTask *task) { if (!task) return; m_ForcedMutex.writeLock(); ThreadPoolThread *thread = new ThreadPoolThread(new ThreadPoolTaskSource(task), true); thread->onCompleteEvent += delegate(this, &ThreadPool::onThreadComplete); m_vForcedList.push_back( thread ); thread->start(); m_ForcedMutex.writeUnlock(); }
void ThreadPool::start(const std::shared_ptr<Job> &job, int priority) { job->mPriority = priority; if (priority == Guaranteed) { ThreadPoolThread *t = new ThreadPoolThread(job); t->start(mPriority, mThreadStackSize); return; } std::lock_guard<std::mutex> lock(mMutex); if (mJobs.empty()) { mJobs.push_back(job); } else { if (mJobs.at(mJobs.size() - 1)->mPriority >= priority) { mJobs.push_back(job); } else if (mJobs.at(0)->mPriority < priority) { mJobs.push_front(job); } else { mJobs.push_back(job); std::sort(mJobs.begin(), mJobs.end(), jobLessThan); } } mCond.notify_one(); }