c++ 11中如何在Mac OS X上命名std::线程
How to name std::thread on Mac OS X in C++11?
我想命名一个线程,但不幸的是,Mac上的pthread_setname_np()
只在当前线程内工作。
然后我用以下构造函数对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
参数外的整个接口?
可以使用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();
}
必须将成员函数绑定到类实例。下面是您的函数,与(工作)测试略有不同:
#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;
}
相关文章:
- 即发即弃 std::线程对象清理自身
- std::线程导致程序中止
- 在std::线程中使用已分配的结构数据
- 使用-static libstdc++时std::线程弱,因此在运行时会导致崩溃
- std::线程与 pthread_setschedparam 与 C++ 11.
- 运行 std::线程不在构造函数中
- C++ std::线程调用方法,从对象原因到调用此类的析构函数
- 编译问题 C++ 同时,尝试通过调用另一个对象中的成员函数来创建 std:: 线程
- 错误:静态断言失败:std ::线程参数必须在转换为rvalues后不可行
- C STD ::线程中的种族状况或内存损坏
- 在 Valgrind 输出中仍然可以访问 std 线程向量的块
- 将类Cotaining std ::线程添加到向量
- 如何使用mingw编译C STD ::线程代码
- 从其他std ::线程更新QT GUI
- STD ::线程不会退出
- 处理 std::线程包装器类的立即销毁
- C++ std 线程并列出分段错误(核心转储)
- 杀死后的STD ::线程如何处理
- 干净取消在输入/输出调用中被阻止的 std::线程
- std ::线程最大并发线程