Terminates thr
and schedules another thread to be run, returning the terminated Thread
. If this is the main thread, or the last thread, exits the process.
Returns the priority of thr. Default is inherited from the current thread which creating the new thread, or zero for the initial main thread; higher-priority thread will run more frequently than lower-priority threads (but lower-priority threads can also run).
This is just hint for Ruby thread scheduler. It may be ignored on some platform.
Thread.current.priority #=> 0
Sets the priority of thr to integer. Higher-priority threads will run more frequently than lower-priority threads (but lower-priority threads can also run).
This is just hint for Ruby thread scheduler. It may be ignored on some platform.
count1 = count2 = 0 a = Thread.new do loop { count1 += 1 } end a.priority = -1 b = Thread.new do loop { count2 += 1 } end b.priority = -2 sleep 1 #=> 1 count1 #=> 622504 count2 #=> 5832
Returns true
if thr
is dead or sleeping.
a = Thread.new { Thread.stop } b = Thread.current a.stop? #=> true b.stop? #=> false
Returns the seed value used to initialize the generator. This may be used to initialize another generator with the same state at a later time, causing it to produce the same sequence of numbers.
prng1 = Random.new(1234) prng1.seed #=> 1234 prng1.rand(100) #=> 47 prng2 = Random.new(prng1.seed) prng2.rand(100) #=> 47
Prevents threads from being added to or removed from the receiving ThreadGroup
.
New threads can still be started in an enclosed ThreadGroup
.
ThreadGroup::Default.enclose #=> #<ThreadGroup:0x4029d914> thr = Thread.new { Thread.stop } #=> #<Thread:0x402a7210 sleep> tg = ThreadGroup.new #=> #<ThreadGroup:0x402752d4> tg.add thr #=> ThreadError: can't move from the enclosed thread group
Returns true
if the thgrp
is enclosed. See also ThreadGroup#enclose
.
Obtains a lock, runs the block, and releases the lock when the block completes. See the example under Mutex
.
Closes the queue. A closed queue cannot be re-opened.
After the call to close completes, the following are true:
closed?
will return true
close
will be ignored.
calling enq/push/<< will raise a ClosedQueueError
.
when empty?
is false, calling deq/pop/shift will return an object from the queue as usual.
when empty?
is true, deq(false) will not suspend the thread and will return nil. deq(true) will raise a ThreadError
.
ClosedQueueError
is inherited from StopIteration
, so that you can break loop block.
Example: q = Queue.new Thread.new{ while e = q.deq # wait for nil to break loop # ... end } q.close
Returns true
if the queue is closed.
Retrieves data from the queue.
If the queue is empty, the calling thread is suspended until data is pushed onto the queue. If non_block
is true, the thread isn’t suspended, and ThreadError
is raised.
Returns true
if the queue is empty.
Removes all objects from the queue.
Similar to Queue#close
.
The difference is behavior with waiting enqueuing threads.
If there are waiting enqueuing threads, they are interrupted by raising ClosedQueueError(‘queue closed’).
Retrieves data from the queue.
If the queue is empty, the calling thread is suspended until data is pushed onto the queue. If non_block
is true, the thread isn’t suspended, and ThreadError
is raised.
Returns true
if the queue is empty.
Removes all objects from the queue.
Path of the file being run
With no arguments, raises the exception in $!
or raises a RuntimeError
if $!
is nil
. With a single String
argument, raises a RuntimeError
with the string as a message. Otherwise, the first parameter should be an Exception
class (or another object that returns an Exception
object when sent an exception
message). The optional second parameter sets the message associated with the exception (accessible via Exception#message
), and the third parameter is an array of callback information (accessible via Exception#backtrace
). The cause
of the generated exception (accessible via Exception#cause
) is automatically set to the “current” exception ($!
), if any. An alternative value, either an Exception
object or nil
, can be specified via the :cause
argument.
Exceptions are caught by the rescue
clause of begin...end
blocks.
raise "Failed to create socket" raise ArgumentError, "No parameters", caller
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise, generate a JSON
text from the Ruby data structure object and return it.
The opts argument is passed through to generate/parse respectively. See generate and parse for their documentation.
Creates a new Pathname
object from the given string, path
, and returns pathname object.
In order to use this constructor, you must first require the Pathname
standard library extension.
require 'pathname' Pathname("/home/zzak") #=> #<Pathname:/home/zzak>
See also Pathname::new
for more information.
Creates an IO
object connected to the given stream, file, or subprocess.
If path
does not start with a pipe character (|
), treat it as the name of a file to open using the specified mode (defaulting to “r”).
The mode
is either a string or an integer. If it is an integer, it must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If it is a string, it is either “fmode”, “fmode:ext_enc”, or “fmode:ext_enc:int_enc”.
See the documentation of IO.new
for full documentation of the mode
string directives.
If a file is being created, its initial permissions may be set using the perm
parameter. See File.new
and the open(2) and chmod(2) man pages for a description of permissions.
If a block is specified, it will be invoked with the IO
object as a parameter, and the IO
will be automatically closed when the block terminates. The call returns the value of the block.
If path
starts with a pipe character ("|"
), a subprocess is created, connected to the caller by a pair of pipes. The returned IO
object may be used to write to the standard input and read from the standard output of this subprocess.
If the command following the pipe is a single minus sign ("|-"
), Ruby forks, and this subprocess is connected to the parent. If the command is not "-"
, the subprocess runs the command.
When the subprocess is Ruby (opened via "|-"
), the open
call returns nil
. If a block is associated with the open call, that block will run twice — once in the parent and once in the child.
The block parameter will be an IO
object in the parent and nil
in the child. The parent’s IO
object will be connected to the child’s $stdin and $stdout. The subprocess will be terminated at the end of the block.
Reading from “testfile”:
open("testfile") do |f| print f.gets end
Produces:
This is line one
Open a subprocess and read its output:
cmd = open("|date") print cmd.gets cmd.close
Produces:
Wed Apr 9 08:56:31 CDT 2003
Open a subprocess running the same Ruby program:
f = open("|-", "w+") if f.nil? puts "in Child" exit else puts "Got: #{f.gets}" end
Produces:
Got: in Child
Open a subprocess using a block to receive the IO
object:
open "|-" do |f| if f then # parent process puts "Got: #{f.gets}" else # child process puts "in Child" end end
Produces:
Got: in Child
Calls select(2) system call. It monitors given arrays of IO
objects, waits until one or more of IO
objects are ready for reading, are ready for writing, and have pending exceptions respectively, and returns an array that contains arrays of those IO
objects. It will return nil
if optional timeout value is given and no IO
object is ready in timeout seconds.
IO.select
peeks the buffer of IO
objects for testing readability. If the IO
buffer is not empty, IO.select
immediately notifies readability. This “peek” only happens for IO
objects. It does not happen for IO-like objects such as OpenSSL::SSL::SSLSocket
.
The best way to use IO.select
is invoking it after nonblocking methods such as read_nonblock, write_nonblock, etc. The methods raise an exception which is extended by IO::WaitReadable
or IO::WaitWritable
. The modules notify how the caller should wait with IO.select
. If IO::WaitReadable
is raised, the caller should wait for reading. If IO::WaitWritable
is raised, the caller should wait for writing.
So, blocking read (readpartial) can be emulated using read_nonblock and IO.select
as follows:
begin result = io_like.read_nonblock(maxlen) rescue IO::WaitReadable IO.select([io_like]) retry rescue IO::WaitWritable IO.select(nil, [io_like]) retry end
Especially, the combination of nonblocking methods and IO.select
is preferred for IO
like objects such as OpenSSL::SSL::SSLSocket
. It has to_io method to return underlying IO
object. IO.select
calls to_io to obtain the file descriptor to wait.
This means that readability notified by IO.select
doesn’t mean readability from OpenSSL::SSL::SSLSocket
object.
The most likely situation is that OpenSSL::SSL::SSLSocket
buffers some data. IO.select
doesn’t see the buffer. So IO.select
can block when OpenSSL::SSL::SSLSocket#readpartial
doesn’t block.
However, several more complicated situations exist.
SSL is a protocol which is sequence of records. The record consists of multiple bytes. So, the remote side of SSL sends a partial record, IO.select
notifies readability but OpenSSL::SSL::SSLSocket
cannot decrypt a byte and OpenSSL::SSL::SSLSocket#readpartial
will block.
Also, the remote side can request SSL renegotiation which forces the local SSL engine to write some data. This means OpenSSL::SSL::SSLSocket#readpartial
may invoke write system call and it can block. In such a situation, OpenSSL::SSL::SSLSocket#read_nonblock
raises IO::WaitWritable
instead of blocking. So, the caller should wait for ready for writability as above example.
The combination of nonblocking methods and IO.select
is also useful for streams such as tty, pipe socket socket when multiple processes read from a stream.
Finally, Linux kernel developers don’t guarantee that readability of select(2) means readability of following read(2) even for a single process. See select(2) manual on GNU/Linux system.
Invoking IO.select
before IO#readpartial
works well as usual. However it is not the best way to use IO.select
.
The writability notified by select(2) doesn’t show how many bytes are writable. IO#write
method blocks until given whole string is written. So, IO#write(two or more bytes)
can block after writability is notified by IO.select
. IO#write_nonblock
is required to avoid the blocking.
Blocking write (write) can be emulated using write_nonblock and IO.select
as follows: IO::WaitReadable
should also be rescued for SSL renegotiation in OpenSSL::SSL::SSLSocket
.
while 0 < string.bytesize begin written = io_like.write_nonblock(string) rescue IO::WaitReadable IO.select([io_like]) retry rescue IO::WaitWritable IO.select(nil, [io_like]) retry end string = string.byteslice(written..-1) end
an array of IO
objects that wait until ready for read
an array of IO
objects that wait until ready for write
an array of IO
objects that wait for exceptions
a numeric value in second
rp, wp = IO.pipe mesg = "ping " 100.times { # IO.select follows IO#read. Not the best way to use IO.select. rs, ws, = IO.select([rp], [wp]) if r = rs[0] ret = r.read(5) print ret case ret when /ping/ mesg = "pong\n" when /pong/ mesg = "ping " end end if w = ws[0] w.write(mesg) end }
produces:
ping pong ping pong ping pong (snipped) ping
Creates an IO
object connected to the given stream, file, or subprocess.
If path
does not start with a pipe character (|
), treat it as the name of a file to open using the specified mode (defaulting to “r”).
The mode
is either a string or an integer. If it is an integer, it must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If it is a string, it is either “fmode”, “fmode:ext_enc”, or “fmode:ext_enc:int_enc”.
See the documentation of IO.new
for full documentation of the mode
string directives.
If a file is being created, its initial permissions may be set using the perm
parameter. See File.new
and the open(2) and chmod(2) man pages for a description of permissions.
If a block is specified, it will be invoked with the IO
object as a parameter, and the IO
will be automatically closed when the block terminates. The call returns the value of the block.
If path
starts with a pipe character ("|"
), a subprocess is created, connected to the caller by a pair of pipes. The returned IO
object may be used to write to the standard input and read from the standard output of this subprocess.
If the command following the pipe is a single minus sign ("|-"
), Ruby forks, and this subprocess is connected to the parent. If the command is not "-"
, the subprocess runs the command.
When the subprocess is Ruby (opened via "|-"
), the open
call returns nil
. If a block is associated with the open call, that block will run twice — once in the parent and once in the child.
The block parameter will be an IO
object in the parent and nil
in the child. The parent’s IO
object will be connected to the child’s $stdin and $stdout. The subprocess will be terminated at the end of the block.
Reading from “testfile”:
open("testfile") do |f| print f.gets end
Produces:
This is line one
Open a subprocess and read its output:
cmd = open("|date") print cmd.gets cmd.close
Produces:
Wed Apr 9 08:56:31 CDT 2003
Open a subprocess running the same Ruby program:
f = open("|-", "w+") if f.nil? puts "in Child" exit else puts "Got: #{f.gets}" end
Produces:
Got: in Child
Open a subprocess using a block to receive the IO
object:
open "|-" do |f| if f then # parent process puts "Got: #{f.gets}" else # child process puts "in Child" end end
Produces:
Got: in Child