unindent class methods
[ruby_posix_mq.git] / lib / posix_mq.rb
blob02a646d07d72454523038050b9bd4de30b98144f
1 # -*- encoding: binary -*-
2 class POSIX_MQ
4   # version of POSIX_MQ, currently 0.6.0
5   VERSION = '0.6.0'
7   # An analogous Struct to "struct mq_attr" in C.
8   # This may be used in arguments for POSIX_MQ.new and
9   # POSIX_MQ#attr=.  POSIX_MQ#attr returns an instance
10   # of this class.
11   #
12   # See the mq_getattr(3) manpage for more information on the values.
13   Attr = Struct.new(:flags, :maxmsg, :msgsize, :curmsgs)
15   # Opens a POSIX message queue and performs operations on the
16   # given block, closing the message queue at exit.
17   # All all arguments are passed to POSIX_MQ.new.
18   def self.open(*args)
19     mq = new(*args)
20     block_given? or return mq
21     begin
22       yield mq
23     ensure
24       mq.close unless mq.closed?
25     end
26   end
28   # Executes the given block upon reception of the next message in an
29   # empty queue.  If the message queue is not empty, then this block
30   # will only be fired after the queue is emptied and repopulated with
31   # one message.
32   #
33   # This block will only be executed upon the arrival of the
34   # first message and must be reset/reenabled for subsequent
35   # notifications.  This block will execute in a separate Ruby
36   # Thread (and thus will safely have the GVL by default).
37   #
38   # This method is only supported on platforms that implement
39   # SIGEV_THREAD functionality in mq_notify(3).  So far we only
40   # know of glibc + Linux supporting this.  Please let us
41   # know if your platform can support this functionality and
42   # are willing to test for us <ruby.posix.mq@librelist.com>
43   def notify(&block)
44     block.arity == 1 or
45       raise ArgumentError, "arity of notify block must be 1"
46     r, w = IO.pipe
47     self.notify_exec(w, Thread.new(r, w, self) do |r, w, mq|
48       begin
49         begin
50           r.read(1) or raise Errno::EINTR
51         rescue Errno::EINTR, Errno::EAGAIN
52           retry
53         end
54         block.call(mq)
55       ensure
56         mq.notify_cleanup
57         r.close rescue nil
58         w.close rescue nil
59       end
60     end)
61     nil
62   end if RUBY_PLATFORM =~ /linux/
64   # There's no point in ever duping a POSIX_MQ object.
65   # All send/receive operations are atomic and only one
66   # native thread may be notified at a time
67   def dup
68     self
69   end
71   # There's no point in ever cloning a POSIX_MQ object.
72   # All send/receive operations are atomic and only one
73   # native thread may be notified at a time
74   alias clone dup
76 end
78 require 'posix_mq_ext'