Search code examples
crubyruby-ffi

Stop a c function with infinite loop from ruby using RubyFFI


Following is my scenario,

    1. I call a c function called 'subscribe' from Ruby using Ruby FFI
    2. The sub function runs infinitely in a while loop
    3. I need a way to stop this subscription from Ruby (Need to stop the c function which runs infinitely)

Ruby

require 'ffi'

module Queue
  extend FFI::Library
  ffi_lib FFI::Library::LIBC
  attach_function :subscribe, [ :void], :void
end

Thread.new { Queue.subscribe() }

c-program

int subscribe(){
   while(true){
     //Do Stuff
   }
}

Any thoughts? Is there a better way to manage this ?


Solution

  • I don't think you should think of this as stopping the function, it's more like stopping the thread the function runs in. Functions can't in general be "stopped"; what would it mean? It can't just disappear, and if it was executing an instruction what should the CPU do then?

    Threads, however, are schedulable units of execution, and they can be destroyed. You need to read up on the thread API you're using (perhaps that Thread.new() call returns something?) and figure it out from there.