[英]How to name std::thread on Mac OS X in C++11?
I want to name a thread, but unfortunately the pthread_setname_np()
on Mac works only inside current thread. 我想命名一个线程,但是不幸的是,Mac上的
pthread_setname_np()
仅在当前线程内有效。
Then I do the wrapper around std::thread
with a following constructor: 然后,我使用以下构造函数对
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...);
});
}
But it doesn't work with class methods: 但这不适用于类方法:
error: called object type '<complex type>' is not a function or function pointer
f(args...);
^
In the code like this: 在这样的代码中:
threads_.emplace_back("Name", &Aggregator<T>::DoPop, this, some_arg);
What is a proper way to wrap the std::thread
and set the thread name, preserving the whole interface excepting the name
argument in the constructor? 包装
std::thread
并设置线程名称,保留整个接口(构造函数中的name
参数除外)的正确方法是什么?
you have to bind your member function to a class instance. 您必须将成员函数绑定到类实例。 here's your function presented slightly differently with a (working) test:
这是与(工作)测试稍有不同的功能:
#include <iostream>
#include <thread>
template <class F, class ... Args>
std::thread launch_named_thread(const char* name, F&& f, Args&&... args) {
return std::thread([name, f, args...]() {
pthread_setname_np(name);
f(args...);
});
}
struct myclass
{
void thread_loop(int i)
{
std::cout << i << std::endl;
}
};
auto main() -> int
{
myclass x;
auto t = launch_named_thread("hello", std::bind(&myclass::thread_loop, &x, 6));
// this could be:
// auto t = launch_named_thread("hello", std::bind(&myclass::thread_loop, &x, std::placeholders::_1), 6);
// the difference is subtle. i'll leave it to you to work out why
t.join();
return 0;
}
You can use std::mem_fn
to call a member function. 您可以使用
std::mem_fn
调用成员函数。 The first argument in args has to be the pointer to the member object. args中的第一个参数必须是指向成员对象的指针。
Example: 例:
#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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.