Module: Thread::Object

Defined in:
lib/thread/object.rb

Overview

Represents Python-style class interfacing thread.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#native_threadThread

Holds Ruby native thread instance.

Returns:

  • (Thread)

    Ruby native thread object



23
24
25
# File 'lib/thread/object.rb', line 23

def native_thread
  @native_thread
end

Instance Method Details

#alive?Boolean

Indicates thread is alive.

Parameters:

  • +true+ (Boolean)

    if it is, false in otherwise

Returns:

  • (Boolean)


77
78
79
# File 'lib/thread/object.rb', line 77

def alive?
    @native_thread.alive?
end

#log(message) ⇒ Object

Logs an message. By overriding this, you can change the format.

Parameters:

  • message (String)

    message for writing out



88
89
90
# File 'lib/thread/object.rb', line 88

def log(message)
    STDERR.write "[" << Time.now.strftime("%Y-%m-%d %H:%M:%S") << "] " << self.class.name << ": " << message.to_s << "\n"
end

#runObject

This method is abstract.

Runs the thread code.

Raises:

  • (Exception)


31
32
33
# File 'lib/thread/object.rb', line 31

def run
    raise Exception::new("Method #run must be overriden. It should contain body of the thread.")
end

#shutdown!Object

Shutdowns the thread.



68
69
70
# File 'lib/thread/object.rb', line 68

def shutdown!
    @native_thread.terminate()
end

#start!(silent = nil) ⇒ Thread

Starts the thread by calling the #run method as in Python. It’s non-blocking, of sure.

Uncacthed rxceptions raised by thread are written out to STDERR by default. This feature can be turned of by the silent argument.

Parameters:

  • silent (nil, :silent) (defaults to: nil)

    indicates, it shouln’t write exceptions out

Returns:

  • (Thread)

    native Ruby thread

See Also:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/thread/object.rb', line 49

def start!(silent = nil)
    @native_thread = Thread::new do
        begin
            self.run()
        rescue ::Exception => e
            if silent != :silent
                self.log "THREAD EXCEPTION! " << e.class.to_s << ": " << e.message
                e.backtrace.each { |i| self.log i }
            end
        end
    end
    
    return @native_thread
end