Question

I'm in the situation, that I have to construct some larger ruby data structures in C++ code from within ruby threads and not ruby threads.

Does ruby objects created on the stack have to be specially treated to not get collected by the ruby GC? Does it make any difference, if the objects are created on a ruby or on a not ruby thread?

Example:

VALUE h = rb_hash_new(); 
VALUE k = rb_str_new2( "foo" );
VALUE v = rb_str_new2( "foo" );
rb_hash_aset( h, k, v );

I would expect that every function call can allocate memory and thus invoke the garbage collector. Do I have to take special care to protect h, k and v from being collected until they are reachable through any global variable? Maybe like this:

VALUE h = Qnil;
VALUE k = Qnil;
VALUE v = Qnil;
rb_gc_register_address( &h ); 
rb_gc_register_address( &k ); 
rb_gc_register_address( &v ); 

VALUE k = rb_str_new2( "foo" );
VALUE v = rb_str_new2( "foo" );

rb_hash_aset( h, k, v );

rb_gc_unregister_address( &k ); 
rb_gc_unregister_address( &v ); 

The second version is much more complicated, so I would like to avoid it, if there is any guaranty that the GC scans all threads for possible references.

Edit: I just realized, that I probably shouldn't use functions like rb_gc... from a not ruby thread that doesn't hold the gvl. So having the guaranty, that the GC will mark references from ruby stacks will be sufficient.

TIA Torsten

Was it helpful?

Solution

As I understand it the GC scans all your stack for anything that looks like a pointer to a ruby object and considers anything it finds in this way as an object that is in use.

Creating ruby objects on a non ruby thread is not something that is supported, as far as I know

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top