#!/usr/local/bin/ruby

# this program uses 3 threads and will generate only about
# 10,000 numbers. It doesn't fail, just doesn't report the
# numbers. The main routine needed to wait for the threads, 
# when the main routine exits all the threads die, so *.join
# is necessary to keep the main thread around while children
# threads finish.

arr1 = Array.new
arr2 = Array.new
arr3 = Array.new

thread = Thread.new {
   puts "In thread 1\n"
   for i in 0..100000
#  for i in 0..20
      arr1[i] = rand(1000) # 1000 is max int
#     printf "generating thd1 cnt = %d\n", i
#     sleep 10 
#     Thread.pass(thd)
   end
   puts "About to print thrd 1\n"
   for i in 0..100000
      if i%10000 == 0 
         printf "arr1[%d] = %d\n",i,arr1[i] 
      end
   end
}

thd = Thread.new {
   puts "In thread 2\n"
   for j in 0..100000
#  for j in 0..20
      arr2[j] = rand(1000) # 1000 is max int
#     printf "generating thd2 cnt = %d\n", j
#     Thread.pass(thread)
      if j%10000 == 0 
         printf "arr1[%d] = %d\n",j,arr1[j] 
      end
   end
   puts "About to print thrd 2\n"
   for j in 0..20
      printf "arr2[%d] = %d\n",j,arr2[j] 
   end
}

thd2 = Thread.new {
   puts "In thread 3\n"
   for j in 0..100000
#  for j in 0..20
      arr3[j] = rand(1000) # 1000 is max int
#     printf "generating thd3 cnt = %d\n", j
#     Thread.pass(thread)
      if j%10000 == 0 
         printf "arr1[%d] = %d\n",j,arr1[j] 
      end
   end
   puts "About to print thrd 3\n"
   for j in 0..20
      printf "arr3[%d] = %d\n",j,arr3[j] 
   end
}

thd.join
thd2.join
thread.join
Published in: Ruby
Download

Related snippets