Skip to content

Instantly share code, notes, and snippets.

@notbend
Last active December 19, 2015 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notbend/6017962 to your computer and use it in GitHub Desktop.
Save notbend/6017962 to your computer and use it in GitHub Desktop.
flat file atomic read/write in progress
require 'thread'
require 'time'
require 'csv'
class FlatfileDb
attr_reader :active_data
def initialize()
@active_data = Array.new
@sem = Mutex.new
end
def id
t = Time.new
return t.to_i, t.nsec.to_i
end
def write(table, data)
raise "no such file" if !File.file? table
Thread.new {
@sem.synchronize {
f = File.open(table, "a")
row = ''
data = [data] if data[0].class != Array # for flat array
data.each do |d|
epoch, nanosec = self.id
row += CSV.generate_line([epoch, nanosec].concat(d))
end
f.write(row)
f.close
}
}
end
def read(table, conditions, limit = 0)
raise "no such file" if !File.file? table
Thread.new {
@sem.synchronize {
f = File.open(table, "r")
f.each do |line|
@active_data.push(line)
end
f.close
}
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment