c++ - 如何在 C++11 的 Mac OS X 上命名 std::thread?

标签 c++ multithreading macos c++11

我想命名一个线程,但不幸的是 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/

相关文章:

java - 安装了 java 7 但终端响应版本 6

c++ - 通过网络测量耗时

c++ - 隐式转换警告 int 到 int-lookalike

c - C Unix 中的段错误(核心转储)

Python GUI 保持卡住等待线程代码完成运行

xcode - 禁用智能引号的 NSTextView,仍然替换引号

c++ - Boost::Math::Quaternion 中的异常防护习语

algorithm - 如何在 C++ (STL) 中否定仿函数?

multithreading - TParallel.For 中的 ASride 是什么意思?

macos - NSTableView 使用自动布局在单元格 View 上创建宽度约束