Last active
December 19, 2015 21:08
-
-
Save notbend/6017962 to your computer and use it in GitHub Desktop.
flat file atomic read/write in progress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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