Class: AlWorker::BroadcastMessage

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

Overview

Broadcast message

(note) スレッド間メッセージングシステム。 1:nメッセージを実現する。 (通常の1:1メッセージであれば、Ruby標準のQueueで十分。)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBroadcastMessage

constructor



33
34
35
# File 'lib/al_worker_message.rb', line 33

def initialize()
  @threads = {}
end

Instance Attribute Details

#threadsHash <Thread,Queue> (readonly)

Returns スレッドとメッセージキュー.

Returns:

  • (Hash <Thread,Queue>)

    スレッドとメッセージキュー



27
28
29
# File 'lib/al_worker_message.rb', line 27

def threads
  @threads
end

Instance Method Details

#attachObject

ブロードキャストメッセージ受信予約



41
42
43
# File 'lib/al_worker_message.rb', line 41

def attach()
  @threads[ Thread.current.object_id ] = [ Thread.current, Queue.new() ]
end

#detachObject

ブロードキャストメッセージ受信予約解除



49
50
51
# File 'lib/al_worker_message.rb', line 49

def detach()
  @threads.delete( Thread.current.object_id )
end

#empty?Boolean

メッセージがあるか問い合わせ

Returns:

  • (Boolean)

    メッセージが無い時、true。



89
90
91
92
93
# File 'lib/al_worker_message.rb', line 89

def empty?()
  @threads[ Thread.current.object_id ][1].empty?()
rescue NoMethodError
  raise "Maybe used empty?() without attach()."
end

#receiveObject

Note:

メッセージ受信

メッセージがなければ、送られるまで停止する。

Returns:

  • (Object)

    受信メッセージ



77
78
79
80
81
# File 'lib/al_worker_message.rb', line 77

def receive()
  @threads[ Thread.current.object_id ][1].pop()
rescue NoMethodError
  raise "Maybe used receive() without attach()."
end

#send(msg) ⇒ Object

メッセージ送信

Parameters:

  • msg (Object)

    送信メッセージ



59
60
61
62
63
64
65
66
67
# File 'lib/al_worker_message.rb', line 59

def send( msg )
  @threads.values.each do |th,q|
    if th.alive?
      q.push( msg )
    else
      @threads.delete( th.object_id )
    end
  end
end