Class: LightIO::Library::Thread::Mutex

Inherits:
Object
  • Object
show all
Extended by:
Base::MockMethods
Defined in:
lib/lightio/library/thread.rb

Instance Method Summary collapse

Constructor Details

#initializeMutex

Returns a new instance of Mutex.



233
234
235
236
237
# File 'lib/lightio/library/thread.rb', line 233

def initialize
  @queue = LightIO::Library::Queue.new
  @queue << true
  @locked_thread = nil
end

Instance Method Details

#lockObject

Raises:



239
240
241
242
243
244
# File 'lib/lightio/library/thread.rb', line 239

def lock
  raise ThreadError, "deadlock; recursive locking" if owned?
  @queue.pop
  @locked_thread = LightIO::Thread.current
  self
end

#locked?Boolean

Returns:

  • (Boolean)


253
254
255
# File 'lib/lightio/library/thread.rb', line 253

def locked?
  !@locked_thread.nil?
end

#owned?Boolean

Returns:

  • (Boolean)


257
258
259
# File 'lib/lightio/library/thread.rb', line 257

def owned?
  @locked_thread == LightIO::Thread.current
end

#sleep(timeout = nil) ⇒ Object



261
262
263
264
265
# File 'lib/lightio/library/thread.rb', line 261

def sleep(timeout=nil)
  unlock
  LightIO.sleep(timeout)
  lock
end

#synchronizeObject

Raises:



267
268
269
270
271
272
273
274
275
# File 'lib/lightio/library/thread.rb', line 267

def synchronize
  raise ThreadError, 'must be called with a block' unless block_given?
  lock
  begin
    yield
  ensure
    unlock
  end
end

#try_lockObject



277
278
279
280
281
282
283
284
# File 'lib/lightio/library/thread.rb', line 277

def try_lock
  if @locked_thread.nil?
    lock
    true
  else
    false
  end
end

#unlockObject

Raises:



246
247
248
249
250
251
# File 'lib/lightio/library/thread.rb', line 246

def unlock
  raise ThreadError, "Attempt to unlock a mutex which is not locked" unless owned?
  @locked_thread = nil
  @queue << true
  self
end