Ruby - async_fu, ease of use of threads

    I have been working with ruby ​​not so long ago, but almost in the early days there was an urgent need to run long-playing functions that should not block the operation of the main program.

    I did not find a ready-made and simple solution, therefore I began to reinvent the wheel.

    At the moment, the library allows you to:
    • organize asynchronous method calls of your class
    • guarantees the execution of all threads before exiting the program


    Usage example:
    Copy Source | Copy HTML
    1. class YourClass1
    2.   def hello
    3.     p 'start'
    4.     p 'list ' + Thread.list.join( ' ')
    5.     p 'main ' + Thread.main.to_s
    6.     p 'this ' + Thread.current.to_s
    7.     p 'end'
    8.   end
    9. end
    10.  
    11. af = AsyncFu.new(YourClass1.new)
    12. af.hello

    Copy Source | Copy HTML
    1. class YourClass2 < AsyncFu
    2.   def hello
    3.     p 'start'
    4.     p 'list ' + Thread.list.join( ' ')
    5.     p 'main ' + Thread.main.to_s
    6.     p 'this ' + Thread.current.to_s
    7.     p 'end'
    8.   end
    9. end
    10.  
    11. ai = YourClass2.new
    12. ai.hello

    You can feel it here: GitHub

    TODO
    • Make sane callback so that you can track the status.
    • Make exception handling and status returns.
    • Make it possible to use mixin style.


    PS It is interesting to listen to the guru :)

    UPD
    The above examples are not a way to use, this is a thread check, a piece of the old test.
    In fact, you can do this:

    Copy Source | Copy HTML
    1. require 'rubygems'
    2. require 'async_fu'
    3.  
    4. class Some
    5.     def grep(query, path)
    6.         list = `grep -rne '#{query}' #{path}`
    7.         File.new( '/tmp/grep.log', 'w' ).write list
    8.     end
    9.     def tick
    10.       loop{
    11.         sleep 1
    12.         p 'tick'
    13.       }
    14.     end
    15.     def tack
    16.       loop{
    17.         sleep 2
    18.         p 'tack'
    19.       }
    20.     end
    21. end
    22.  
    23. test = AsyncFu.new(Some.new)
    24. test.tick
    25. test.grep( 'thread.rb', '/usr/local/lib' )
    26. test.tack

    Also popular now: