Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =begin
- The purpose of this code was to write a little practice program that would enable me to generate a thread safe way of writing strings to a logfile. I would also like to use the Queue with my threads. I read that it was thread safe in my handbook. The reason why this is helpful is because it is more efficient to buffer a fixed number of reports before writing it to a file rather than continuously writing to a file every time a single string is received. As you can see, I haven't even gotten to a point where I could write to a file. For some reason, I never seem to get the first thread inside of the synchronize method inside of thread_queuetest(). I am open to any suggestions. Sorry if this is pretty complicated.
- =end
- require 'thread'
- require 'monitor'
- class ReportManagement
- def Initialize()
- @queuemax = 256
- @queue = queue.new
- @queue.extend(MonitorMixin)
- @maxed_reports_cond = @queue.new_cond
- @shutdown_ok = false
- end
- def ts_reportlogs(outfile)
- if(outfile.class != File)
- print "invalid arguments passed into ReportManagement::ts_reportlogs()\n"
- exit
- end
- report_thread = Thread.new(outfile) {
- loop do
- @queue.synchronize do
- @maxed_reports_cond.wait_while {@queue.empty?}
- res = @queue.pop
- print "[!] Report #{Thread.current} dequeued #{res} from report buffer.\n"
- end
- end
- }
- end
- def self.open_logfile(filename=nil)
- filename ||= get_filename_from_time
- outfile = File.new(filename, File::WRONLY|File::CREAT|File::APPEND)
- return outfile
- end
- def thread_queuetest()
- threads = []
- 1000.times do |x|
- threads << Thread.new(x) {
- @queue.synchronize do
- if(@shutdown_ok && queue.empty?)
- break
- elsif(@queue.length >= @queuemax)
- @maxed_reports_cond.signal
- @queue.wait_while {@queue.length >= @queuemax}
- end
- @queue.enq("\"#{x} hello from #{Thread.current}\"")
- end
- }
- end
- threads.join
- end
- protected
- def self.get_filename_from_time
- t = Time.now()
- filename = t.strftime("%Y.%m.%d.%H.%M.%S.log")
- end
- end
- # instantiate the object that will manage a thread safe logging system
- myobject = ReportManagement.new
- # generate an output file for logging
- outfile = ReportManagement.open_logfile()
- # populate a queue with simulated results from multithreaded tasks
- myqueue = myobject.thread_queuetest()
- # This is where we do the real work - write results to a file...
- # in a threadsafe manner using mixins (signals/cond variables)
- myobject.ts_reportlogs(outfile)
- @shutdown_ok = true
Add Comment
Please, Sign In to add comment