How to get number of active threads in C?

Hi all,

I’m writing a Ruby C extension and I need a fast way to get the number
of active threads. I got something working for 1.8.6 but it’s not
portable to other Ruby version like 1.9 (because I can’t include the
header for rb_thread_t struct and the like) and it doesn’t look very
sane.

Here’s my code for Ruby 1.8.6:

#include “node.h”

rb_thread_t mainth = (rb_thread_t) RDATA(rb_thread_main())->data;
rb_thread_t th = mainth;
size_t num_threads = 0;

do {
th = th->next;
if (th->status != THREAD_KILLED)
num_threads ++;
} while (th != mainth);

printf("%d active threads\n", num_threads);

I’m wondering if there’s a better way to do this. I know there’s the
rb_thread_list, but I would like to avoid creating a new Ruby Array on
each call.

Any suggestion?
thx,
Marc

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs