Ruby threads calling the same function with different arguments

I call the same Ruby function with multiple threads (e.g. 10 threads). Each thread passes different arguments to the function.

Example:

def test thread_no  
    puts "In thread no." + thread_no.to_s
end

num_threads = 6
threads=[]

for thread_no in 1..num_threads
    puts "Creating thread no. "+thread_no.to_s
    threads << Thread.new{test(thread_no)}
end

threads.each { |thr| thr.join }

Conclusion: Creating a stream. 1 Create a stream. 2 Create a stream. 3 Create a stream. 4 Topic 4:
 Creating a stream. 5 Create a stream. 6 Topic β„–6
 Topic β„–6
 Topic β„–6
 Topic β„–6
 In stream β„–6

Of course, I want to get the output: In thread no. 1 (2,3,4,5,6) Can I somehow make it work?

+4
source share
2 answers

for -loop. Ruby . , . 6 . .

, each -loops. , .

(1..num_threads).each do | thread_no |
    puts "Creating thread no. "+thread_no.to_s
    threads << Thread.new{test(thread_no)}
end

, for . each.

: Thread.new , . , , vars , for-loops.

threads <<  Thread.new(thread_no){|n| test(n) }
+3

@Meier , for-end , .

for loop - , thread_no thread_no 6, for , .

, thread_no - ,

def test thread_no
  puts "In thread no." + thread_no.to_s
end

num_threads = 6
threads     = []

for thread_no in 1..num_threads
  threads << -> (thread_no) { Thread.new { test(thread_no) } }.  (thread_no)
end

threads.each { |thr| thr.join }
0

Source: https://habr.com/ru/post/1615188/


All Articles