Class: Codebot::ThreadController

Inherits:
Object
  • Object
show all
Defined in:
lib/codebot/thread_controller.rb

Overview

This class provides a consistent interface for subclasses that manage a thread.

Direct Known Subclasses

IPCServer, IRCConnection, WebServer

Instance Method Summary collapse

Constructor Details

#initializeThreadController

Creates a new thread controller.



8
9
10
# File 'lib/codebot/thread_controller.rb', line 8

def initialize
  @thread = nil
end

Instance Method Details

#joinThread?

Suspends execution of the calling thread until the managed thread exits.

Returns:

  • (Thread, nil)

    the dead thead, or nil if no thread was active



15
16
17
# File 'lib/codebot/thread_controller.rb', line 15

def join
  @thread.join if running?
end

#running?Boolean

Checks whether the managed thread is currently running.

Returns:

  • (Boolean)

    true if the managed thread is alive, false otherwise



23
24
25
# File 'lib/codebot/thread_controller.rb', line 23

def running?
  !@thread.nil? && @thread.alive?
end

#start(arg = nil) ⇒ Thread?

Starts a new managed thread if no thread is currently running. The thread invokes the run method of the class that manages it.

Parameters:

  • arg (defaults to: nil)

    the argument to pass to the #run method

Returns:

  • (Thread, nil)

    the newly created thread, or nil if there was already a running thread



33
34
35
36
37
38
39
40
# File 'lib/codebot/thread_controller.rb', line 33

def start(arg = nil)
  return if running?

  @thread = Thread.new do
    Thread.current.abort_on_exception = true
    run(arg)
  end
end

#start!(arg = nil) ⇒ Thread

Starts a new managed thread. The thread invokes the run method of the class that manages it.

Parameters:

  • arg (defaults to: nil)

    the argument to pass to the run method

Returns:

  • (Thread)

    the newly created thread

Raises:

  • (RuntimeError)

    if there was already a running thread



48
49
50
# File 'lib/codebot/thread_controller.rb', line 48

def start!(arg = nil)
  raise "#{self.class.name} is already running" unless start(arg)
end

#stopThread?

Stops the managed thread if a thread is currently running.

Returns:

  • (Thread, nil)

    the stopped thread, or nil if no thread was running



56
57
58
59
60
# File 'lib/codebot/thread_controller.rb', line 56

def stop
  return unless running?

  @thread.exit
end

#stop!Thread

Stops the managed thread.

Returns:

  • (Thread)

    the stopped thread

Raises:

  • (RuntimeError)

    if there was no running thread



66
67
68
# File 'lib/codebot/thread_controller.rb', line 66

def stop!
  raise "#{self.class.name} is already stopped" unless stop
end