Tushar Khan
Tushar Khan

Reputation: 33

How to Create Multiple thread instantly in ruby?

Is it possible to create and execute multiple threads at a same time?

e.g. Creating 2 threads requires to write Thread.new 2 times and then .join line. but what if i want to create 50 threads doing same thing. Is it possible to create 50 thread without typing each thread separately?

for eg.

to print "a" on screen twice but "instantly" at a same time, I need this lines:

t1=Thread.new{print "a"}

t2=Thread.new{print "a"}

t1.join

t2.join

output ==> aa


but what if i want to print "a" 50 times on screen instantly without typing thread.new 50 times? How can i do this, creating and executing 50 threads instantly, please help.

Upvotes: 1

Views: 522

Answers (1)

lurker
lurker

Reputation: 58234

Perhaps you could use an array:

threads = Array.new
50.times { threads << Thread.new { print "a" } }
50.times { threads.pop.join }

Upvotes: 1

Related Questions