- methods to expand tilda in file pathes + methods to control thread pool

This commit is contained in:
Dmytro Bogovych 2024-05-16 08:42:55 +03:00
parent 05e3cc8cb6
commit 62f2d996c6
4 changed files with 46 additions and 4 deletions

View File

@ -109,3 +109,32 @@ size_t FileHelper::getFreespace(const std::string& path)
#endif
return r;
}
std::string FileHelper::expandUserHome(const std::string &path)
{
if (path.empty() || path[0] != '~')
return path; // No expansion needed
const char* home_dir = nullptr;
#ifdef TARGET_WIN
home_dir = std::getenv("USERPROFILE");
if (!home_dir)
{
home_dir = std::getenv("HOMEDRIVE");
const char* homepath = std::getenv("HOMEPATH");
if (home_dir && homepath) {
std::string fullpath(home_dir);
fullpath += homepath;
return fullpath + path.substr(1);
}
}
#else
home_dir = std::getenv("HOME");
#endif
if (!home_dir)
throw std::runtime_error("Unable to determine the home directory");
return std::string(home_dir) + path.substr(1);
}

View File

@ -23,6 +23,7 @@ public:
// Returns free space on volume for path
// Works for Linux only. For other systems (size_t)-1 is returned (for errors too)
static size_t getFreespace(const std::string& path);
static std::string expandUserHome(const std::string& path);
};
#endif

View File

@ -20,6 +20,17 @@ void thread_pool::enqueue(const thread_pool::task& t)
this->condition.notify_one();
}
void thread_pool::wait(std::chrono::milliseconds interval)
{
while (size() != 0)
std::this_thread::sleep_for(interval);
}
size_t thread_pool::size()
{
std::unique_lock l(this->queue_mutex);
return this->tasks.size();
}
// the destructor joins all threads
thread_pool::~thread_pool()
@ -37,7 +48,7 @@ void thread_pool::run_worker()
{
ThreadHelper::setName(this->name);
task t;
while(!this->stop)
while (!this->stop)
{
{
std::unique_lock<std::mutex> lock(this->queue_mutex);

View File

@ -18,11 +18,12 @@ class thread_pool
public:
typedef std::function<void()> task;
thread_pool(size_t num_of_threads, const std::string&);
thread_pool(size_t num_of_threads, const std::string& thread_name);
~thread_pool();
void enqueue(const task& task);
void wait(std::chrono::milliseconds interval = std::chrono::milliseconds(50));
size_t size();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
@ -33,7 +34,7 @@ private:
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop = false;
std::atomic_bool stop = false;
// thread name prefix for worker threads
std::string name;