Threads not concurrent

Hi my code looks like:
================few lines of codes
childredn=[]
for i in 1…2
children[i-1]=Thread.new do
DRb.start_service
server_uri=ARGV.shift
server = DRbObject.new nil, server_uri
puts “A new thread created----------------------” #line alpha
while !server.get_stop_flag
sleep(i)
puts “inside loop----------------------”
begin
obj=server.get_object_s
if !(Obj===obj and obj!=nil)
sleep(6)
next
end
process=Process.new(obj)
process.process_on()
processed_obj=process.obj
server.update_obj(processed_obj)
rescue => e
$logger.log_it("Error in client, ", e.message)
end
end
puts “–A thread completed”
end
end

children.each do |t|
if t!=nil
t.join
end
end
================few lines of codes

#---------------
The sequence of print is like:
puts “A new thread created----------------------”
puts “A new thread created----------------------”
puts “inside loop----------------------”
–A thread completed
puts “inside loop----------------------”
–A thread completed

But I want:
puts “A new thread created----------------------”
puts “A new thread created----------------------”
puts “inside loop----------------------”
puts “inside loop----------------------”
–A thread completed
–A thread completed

For your information I have used ‘system’ to start this block of script
from another ruby script.

The blocked thread is blocked at #line alpha, i.e #line alpha is
executed, after that it stops (not killed but paused.)

Odd as it sounds, try printing to stderr and not stdout. Stdout is
buffered and not reliable when trying to see thread output in real time.

That may not get your current issue, but it’ll be a good start.

Hi, Ajay!

Your process of updating server i.e. the following code:

    process=Process.new(obj)
    process.process_on()
    processed_obj=process.obj
    server.update_obj(processed_obj)

is taking different times to complete in the two threads. Hopefully, you
can fix this by trying to tweak the {{ sleep(6) }}. For example the
following code (of course in your version) may fix your problem:

#!/usr/bin/env ruby
children=[]
for i in 1…2
children[i-1]=Thread.new do
stop_flag = false
puts “A new thread created----------------------” #line alpha
while !stop_flag
sleep(i)
puts “inside loop----------------------”

  sleep(i==2?6:1)  # <<< This will fix your problem
  stop_flag = true
  next
end
puts "--A thread completed"

end
sleep 0.5 # <<< Try delaying creation of threads for short time
end
children.each { |t| t.join }

Regards, igor

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs