Threading from a loop

N

Nicholas Poole

Hi,

My problem is that I want a function to start as a new thread every time
it's called, hence allowing the loop to continue and spawn a thread for
each iteration of the loop. Currently my loop waits for the function to
end before it continues. If anyone can anyone tell me what I'm missing,
or even refer me to some good documentation, I'd be grateful.

My current code is as follows:

cl.add_message_callback do |m|
if m.type != :error
#break off
newreplythread = Thread.new(cl, m) {
#function call is here
}
end
}

(Maybe I'm mistaking the loop for something else, but it's behaviour
apears the same)


Thanks

NickPoole
 
7

7stud --

Nicholas said:
Hi,

My problem is that I want a function to start as a new thread every time
it's called, hence allowing the loop to continue and spawn a thread for
each iteration of the loop. Currently my loop waits for the function to
end before it continues. If anyone can anyone tell me what I'm missing,
or even refer me to some good documentation, I'd be grateful.

My current code is as follows:

cl.add_message_callback do |m|
if m.type != :error
#break off
newreplythread = Thread.new(cl, m) {
#function call is here
}
end
}

(Maybe I'm mistaking the loop for something else, but it's behaviour
apears the same)

Try this:

def greet
puts 'hello'
end


threads = []

5.times do |i|
threads << Thread.new do
sleep(rand() * 10)
puts "thread#{i}"
greet
puts
end
puts "loop#{i}"
end
puts

threads.each{|thr| thr.join}

--output:--
loop0
loop1
loop2
loop3
loop4 #Note that all loop iterations are completed

thread3
hello

thread0
hello

thread4
hello

thread1
hello

thread2
hello
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,270
Messages
2,571,351
Members
48,036
Latest member
nickwillsonn

Latest Threads

Top