Make Downloader thread safe.

This commit is contained in:
Matthieu Gautier 2023-02-07 10:51:42 +01:00
parent d1fe1b89ae
commit 52ae5c3a5f
2 changed files with 11 additions and 1 deletions

View File

@ -25,6 +25,7 @@
#include <map>
#include <memory>
#include <stdexcept>
#include <mutex>
namespace kiwix
{
@ -95,10 +96,11 @@ class Downloader
Download* startDownload(const std::string& uri, const std::vector<std::pair<std::string, std::string>>& options = {});
Download* getDownload(const std::string& did);
size_t getNbDownload() { return m_knownDownloads.size(); }
size_t getNbDownload();
std::vector<std::string> getDownloadIds();
private:
std::mutex m_lock;
std::map<std::string, std::unique_ptr<Download>> m_knownDownloads;
std::shared_ptr<Aria2> mp_aria;
};

View File

@ -156,6 +156,7 @@ void Downloader::close()
}
std::vector<std::string> Downloader::getDownloadIds() {
std::unique_lock<std::mutex> lock(m_lock);
std::vector<std::string> ret;
for(auto& p:m_knownDownloads) {
ret.push_back(p.first);
@ -165,6 +166,7 @@ std::vector<std::string> Downloader::getDownloadIds() {
Download* Downloader::startDownload(const std::string& uri, const std::vector<std::pair<std::string, std::string>>& options)
{
std::unique_lock<std::mutex> lock(m_lock);
for (auto& p: m_knownDownloads) {
auto& d = p.second;
auto& uris = d->getUris();
@ -179,6 +181,7 @@ Download* Downloader::startDownload(const std::string& uri, const std::vector<st
Download* Downloader::getDownload(const std::string& did)
{
std::unique_lock<std::mutex> lock(m_lock);
try {
return m_knownDownloads.at(did).get();
} catch(std::exception& e) {
@ -198,4 +201,9 @@ Download* Downloader::getDownload(const std::string& did)
}
}
size_t Downloader::getNbDownload() {
std::unique_lock<std::mutex> lock(m_lock);
return m_knownDownloads.size();
}
}