Backtracing a collection of threads

Updated: October 28, 2024

Occasionally, it may be useful to backtrace a collection of threads in a coherent manner. You can accomplish this by freezing all the threads, backtracing the threads, and then unfreezing them. For example:

bt_accessor_t acc;
int count;

hold_all_threads();

for (i=0; i < max_thread; i++) {
    if (bt_init_accessor(&acc, BT_PROCESS, pid, i) == -1)
    {
      fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
               "bt_init_accessor", errno, strerror(errno));
      return -1;
    }

    if (bt_set_flags(&acc, BTF_LIVE_BACKTRACE, 1) == -1)
    {
      fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
               "bt_set_flags", errno, strerror(errno));
      return -1;
    }

    count = bt_get_backtrace(&acc, addrs, len);
    ...

    if (bt_release_accessor(&acc) == -1)
    {
      fprintf( stderr, "%s:%i %s (%i)%s\n", __FUNCTION__, __LINE__,
               "bt_release_accessor", errno, strerror(errno));
      return -1;
    }

    save_addrs(addrs);
}

cont_all_threads();
  翻译: