我想命名一个线程,但不幸的是 pthread_setname_np()
在 Mac 上只能在当前线程内工作。
然后我使用以下构造函数围绕 std::thread
进行包装:
template <class F, class ... Args>
Thread::Thread(const char* name, F&& f, Args&&... args) {
thread_ = std::thread([name, f, args...]() {
pthread_setname_np(name);
f(args...);
});
}
但它不适用于类方法:
error: called object type '<complex type>' is not a function or function pointer
f(args...);
^
在这样的代码中:
threads_.emplace_back("Name", &Aggregator<T>::DoPop, this, some_arg);
什么是包装 std::thread
并设置线程名称的正确方法,在构造函数中保留除 name
参数之外的整个接口(interface)?
最佳答案
您可以使用std::mem_fn
来调用成员函数。 args 中的第一个参数必须是指向成员对象的指针。
例子:
#include <thread>
#include <functional>
template <class F, class ... Args>
std::thread thread_factory(const char* name, F&& f, Args&&... args) {
return std::thread([=]{
pthread_setname_np(name);
auto fun = std::mem_fn(f);
fun(args...);
});
}
struct test {
int t(int val) {
return val;
}
};
int main() {
test t;
auto b = thread_factory("name", &test::t, &t, 5);
b.join();
}
关于c++ - 如何在 C++11 的 Mac OS X 上命名 std::thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31897364/