# How to get number of active threads in C?

**URL:** <https://www.ruby-forum.com/t/how-to-get-number-of-active-threads-in-c/134959>\
**Category:** Ruby\
**Created:** [April 16, 2008, 4:47pm UTC](https://www.ruby-forum.com/t/how-to-get-number-of-active-threads-in-c/134959 "2008-04-16T16:47:21Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![macournoyer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e495f1/32.png) [@macournoyer](https://www.ruby-forum.com/u/macournoyer)\
**Post date:** [April 16, 2008, 4:47pm UTC](https://www.ruby-forum.com/t/how-to-get-number-of-active-threads-in-c/134959/1 "2008-04-16T16:47:21Z")

</div>

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
