Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/namedthread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ std::map<std::thread::id, std::string> threadId2NameMap_;

} // unnamed namespace


std::mutex& NamedThread::getMutex()
{
return mutex_;
}

NamedThread::NamedThread(const std::string& name)
: name_(name)
{
Expand Down
22 changes: 18 additions & 4 deletions src/namedthread.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#ifndef OPENZIM_LIBZIM_NAMEDTHREAD_H
#define OPENZIM_LIBZIM_NAMEDTHREAD_H

#include <mutex>
#include <string>
#include <thread>

Expand All @@ -34,11 +35,18 @@ class LIBZIM_PRIVATE_API NamedThread
explicit NamedThread(const std::string& name);

public:
template <class F, class... Args>
NamedThread(const std::string& name, F&& f, Args&&... args)
template <class F>
NamedThread(const std::string& name, F&& f)
: NamedThread(name)
{
thread_ = std::thread(std::forward<F>(f), std::forward<Args>(args)...);
// Ensure that f starts executing after the assignment to
// the thread_ data member has completed (so that any possible
// calls to NamedThread::getCurrentThreadName() from inside f()
// read the correct value of thread id).
std::mutex& mutex = getMutex();
std::lock_guard<std::mutex> lock(mutex);

thread_ = std::thread([f, &mutex]() { mutex.lock(); mutex.unlock(); f(); });
}

~NamedThread();
Expand All @@ -50,7 +58,13 @@ class LIBZIM_PRIVATE_API NamedThread

static std::string getCurrentThreadName();

private:
private: // functions
// This is a workaround for a bug in our build system that prevents
// LIBZIM_PRIVATE_API and/or LIBZIM_API classes from having static data
// members
static std::mutex& getMutex();

private: // data
const std::string name_;
std::thread thread_;
};
Expand Down