How can you get the Linux thread Id of a std::thread()

前端 未结 3 734
说谎
说谎 2021-02-07 12:09

I was playing with std::thread and I was wondering how is it possible to get the thread id of a new std::thread(), I am not talking about std::t

3条回答
  •  野性不改
    2021-02-07 12:27

    Assuming you're using GCC standard library, std::thread::native_handle() returns the pthread_t thread ID returned by pthread_self(), not the OS thread ID returned by gettid(). std::thread::id() is a wrapper around that same pthread_t, and GCC's std::thread doesn't provide any way to get the OS thread ID, but you could create your own mapping:

    std::mutex m;
    std::map threads;
    void add_tid_mapping()
    {
      std::lock_guard l(m);
      threads[std::this_thread::get_id()] = syscall(SYS_gettid);
    }
    void wrap(void (*f)())
    {
      add_tid_mapping();
      f();
    }
    

    Then create your thread with:

    std::thread t1(&wrap, &SayHello);
    

    then get the ID with something like:

    pid_t tid = 0;
    while (tid == 0)
    {
      std::lock_guard l(m);
      if (threads.count(t1.get_id()))
        tid = threads[t1.get_id()];
    }
    

提交回复
热议问题