File tree Expand file tree Collapse file tree 2 files changed +24
-4
lines changed
Expand file tree Collapse file tree 2 files changed +24
-4
lines changed Original file line number Diff line number Diff line change @@ -38,6 +38,12 @@ std::map<std::thread::id, std::string> threadId2NameMap_;
3838
3939} // unnamed namespace
4040
41+
42+ std::mutex& NamedThread::getMutex ()
43+ {
44+ return mutex_;
45+ }
46+
4147NamedThread::NamedThread (const std::string& name)
4248 : name_(name)
4349{
Original file line number Diff line number Diff line change 2020#ifndef OPENZIM_LIBZIM_NAMEDTHREAD_H
2121#define OPENZIM_LIBZIM_NAMEDTHREAD_H
2222
23+ #include < mutex>
2324#include < string>
2425#include < thread>
2526
@@ -34,11 +35,18 @@ class LIBZIM_PRIVATE_API NamedThread
3435 explicit NamedThread (const std::string& name);
3536
3637public:
37- template <class F , class ... Args >
38- NamedThread (const std::string& name, F&& f, Args&&... args )
38+ template <class F >
39+ NamedThread (const std::string& name, F&& f)
3940 : NamedThread(name)
4041 {
41- thread_ = std::thread (std::forward<F>(f), std::forward<Args>(args)...);
42+ // Ensure that f starts executing after the assignment to
43+ // the thread_ data member has completed (so that any possible
44+ // calls to NamedThread::getCurrentThreadName() from inside f()
45+ // read the correct value of thread id).
46+ std::mutex& mutex = getMutex ();
47+ std::lock_guard<std::mutex> lock (mutex);
48+
49+ thread_ = std::thread ([f, &mutex]() { mutex.lock (); mutex.unlock (); f (); });
4250 }
4351
4452 ~NamedThread ();
@@ -50,7 +58,13 @@ class LIBZIM_PRIVATE_API NamedThread
5058
5159 static std::string getCurrentThreadName ();
5260
53- private:
61+ private: // functions
62+ // This is a workaround for a bug in our build system that prevents
63+ // LIBZIM_PRIVATE_API and/or LIBZIM_API classes from having static data
64+ // members
65+ static std::mutex& getMutex ();
66+
67+ private: // data
5468 const std::string name_;
5569 std::thread thread_;
5670};
You can’t perform that action at this time.
0 commit comments