Code cleanup

This commit is contained in:
ZehMatt 2018-04-24 13:23:14 +02:00 committed by Aaron van Geffen
parent 64d9109226
commit b9e0eede44
2 changed files with 34 additions and 23 deletions

View File

@ -245,7 +245,7 @@ private:
jobPool.join([&]() jobPool.join([&]()
{ {
size_t completed = totalCount - jobPool.countPending(); size_t completed = totalCount - jobPool.countPending();
Console::WriteFormat("File %5d of %d, done %3d%%\r", completed, totalCount, completed / totalCount); Console::WriteFormat("File %5d of %d, done %3d%%\r", completed, totalCount, completed * 100 / totalCount);
}); });
for (auto&& itr : containers) for (auto&& itr : containers)

View File

@ -23,6 +23,7 @@
#include <functional> #include <functional>
#include <atomic> #include <atomic>
#include <vector> #include <vector>
#include <cassert>
class JobPool class JobPool
{ {
@ -65,8 +66,8 @@ public:
for (auto&& th : _threads) for (auto&& th : _threads)
{ {
if (th.joinable()) assert(th.joinable() != false);
th.join(); th.join();
} }
} }
@ -87,27 +88,18 @@ public:
void join(std::function<void()> reportFn = nullptr) void join(std::function<void()> reportFn = nullptr)
{ {
unique_lock lock(_mutex);
while (true) while (true)
{ {
unique_lock lock(_mutex); // Wait for the queue to become empty or having completed tasks.
_condComplete.wait(lock, [this]() _condComplete.wait(lock, [this]()
{ {
return (_pending.empty() && _processing == 0) || !_completed.empty(); return (_pending.empty() && _processing == 0) ||
!_completed.empty();
}); });
if (reportFn) // Dispatch all completion callbacks if there are any.
{ while (!_completed.empty())
reportFn();
}
if (_completed.empty() &&
_pending.empty() &&
_processing == 0)
{
break;
}
if (!_completed.empty())
{ {
auto taskData = _completed.front(); auto taskData = _completed.front();
_completed.pop_front(); _completed.pop_front();
@ -121,6 +113,23 @@ public:
lock.lock(); lock.lock();
} }
} }
if (reportFn)
{
lock.unlock();
reportFn();
lock.lock();
}
// If everything is empty and no more work has to be done we can stop waiting.
if (_completed.empty() &&
_pending.empty() &&
_processing == 0)
{
break;
}
} }
} }
@ -132,12 +141,15 @@ public:
private: private:
void processQueue() void processQueue()
{ {
while (true) unique_lock lock(_mutex);
do
{ {
unique_lock lock(_mutex); // Wait for work or cancelation.
_condPending.wait(lock, [this]() { _condPending.wait(lock, [this]()
{
return _shouldStop || !_pending.empty(); return _shouldStop || !_pending.empty();
}); });
if (!_pending.empty()) if (!_pending.empty())
{ {
_processing++; _processing++;
@ -156,8 +168,7 @@ private:
_processing--; _processing--;
_condComplete.notify_one(); _condComplete.notify_one();
} }
if (_shouldStop)
break;
} }
while(!_shouldStop);
} }
}; };