60 lines
1.6 KiB
C++
60 lines
1.6 KiB
C++
//
|
|
// Created by versustune on 24.02.20.
|
|
//
|
|
|
|
#include "ThreadPool.h"
|
|
#include "../Utils/Logging.h"
|
|
#include "ThreadSafeDeque.h"
|
|
|
|
#include <thread>
|
|
#include <sstream>
|
|
#include <zconf.h>
|
|
|
|
void ThreadPool::setQueue(Tsqueue<std::shared_ptr<ThreadQueueItem>> *queue) {
|
|
ThreadPool::threadQueue = queue;
|
|
}
|
|
|
|
void ThreadPool::initThreads() {
|
|
threadCount = std::thread::hardware_concurrency();
|
|
std::stringstream stream;
|
|
stream << "Create Threadpool with " << threadCount << " threads";
|
|
Logging::log(stream.str().c_str(), "ThreadPool");
|
|
threads.resize(threadCount);
|
|
threads.clear();
|
|
finishedThreads.clear();
|
|
for (int i = 0; i < threadCount; ++i) {
|
|
threads[i] = new std::thread(&ThreadPool::execute, this, i);
|
|
threads[i]->detach();
|
|
}
|
|
|
|
}
|
|
|
|
void ThreadPool::start(ProgressBar *progressBar) {
|
|
initThreads();
|
|
progressBar->startThread();
|
|
while (finishedThreads.size() < threadCount) {
|
|
//wait for threads to finish
|
|
std::this_thread::sleep_for(std::chrono::microseconds(1000));
|
|
}
|
|
progressBar->update();
|
|
}
|
|
|
|
void ThreadPool::execute(int threadNumber) {
|
|
//if queue empty terminate Thread... make no sense ;)
|
|
if (threadQueue->getSize() < 1) {
|
|
return;
|
|
}
|
|
while (auto queueItem = threadQueue->pop()) {
|
|
auto item = queueItem.value();
|
|
if (item == nullptr) {
|
|
continue;
|
|
}
|
|
auto file = item->reader->files[item->fileIndex];
|
|
auto wait = 10000L+(long)((1e5-1e4)*random()/(RAND_MAX+1.0));
|
|
usleep(wait);
|
|
//do your job here!
|
|
item->progressBar->tick();
|
|
}
|
|
finishedThreads.push_back(threadNumber + 1);
|
|
}
|