Skip to content

Commit

Permalink
Added the code for a thread-safe data structure
Browse files Browse the repository at this point in the history
  • Loading branch information
mhakeem committed Apr 29, 2014
1 parent 11bbb71 commit dec00ae
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
26 changes: 26 additions & 0 deletions blocking_queue/complete.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require "thread"

class BlockingQueue
def initialize
@storage = Array.new
@mutex = Mutex.new
@condvar = ConditionalVariable.new
end

def push(item)
@mutex.synchronize do
@storage.push(item)
@condvar.signal
end
end

def pop
@mutex.synchronize do
while @storage.empty?
@condvar.wait(@mutex)
end

@storage.shift
end
end
end
20 changes: 20 additions & 0 deletions blocking_queue/pre_condvar.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
require "thread"

class BlockingQueue
def initialize
@storage = Array.new
@mutex = Mutex.new
end

def push(item)
@mutex.synchronize do
@storage.push(item)
end
end

def pop
@mutex.synchronize do
@storage.shift
end
end
end
13 changes: 13 additions & 0 deletions blocking_queue/pre_mutex.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class BlockingQueue
def initialize
@storage = Array.new
end

def push(item)
@storage.push(item)
end

def pop
@storage.shift
end
end

0 comments on commit dec00ae

Please sign in to comment.