~ubuntu-branches/ubuntu/lucid/jruby/lucid

« back to all changes in this revision

Viewing changes to bench/bench_threaded_reverse.rb

  • Committer: Bazaar Package Importer
  • Author(s): Sebastien Delafond
  • Date: 2009-12-09 17:30:55 UTC
  • Revision ID: james.westby@ubuntu.com-20091209173055-8ffzikq1768gywux
Tags: upstream-1.3.1
ImportĀ upstreamĀ versionĀ 1.3.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
require 'thread'
 
2
 
 
3
class ThreadScalability
 
4
  def initialize()
 
5
    @mutex = Mutex.new
 
6
    @cond_var = ConditionVariable.new
 
7
    @num_ready_threads = 0
 
8
    @num_threads = 0
 
9
    @array_size = 120
 
10
    @array = []
 
11
    value = "0123456789" * 10000
 
12
    @array_size.times {|count|
 
13
      @array[count] = value.clone
 
14
    }
 
15
  end
 
16
 
 
17
  def reverse_string(s)
 
18
    len = s.length
 
19
    (len/2).times { |i|
 
20
      tmp = s[i]
 
21
      s[i] = s[len -1 - i]
 
22
      s[len -1 -i] = tmp
 
23
    }
 
24
    return s
 
25
  end
 
26
 
 
27
  def do_test()
 
28
    concurrency = @num_threads
 
29
    num_ops_per_thread = @array_size/@num_threads
 
30
    threads = []
 
31
    puts "concurrency is - #{concurrency}"
 
32
    concurrency.times { |i|
 
33
      threads << Thread.new {
 
34
        puts "started thread #{i}"
 
35
        
 
36
        # make sure all the threads start at the same time.
 
37
        @mutex.synchronize {
 
38
          @num_ready_threads += 1
 
39
          @cond_var.wait(@mutex) while @num_ready_threads < @num_threads
 
40
          @cond_var.signal if @num_ready_threads == @num_threads
 
41
        }
 
42
        
 
43
        puts "Thread #{i} running"
 
44
 
 
45
        #now do the work.
 
46
        reverse_strings(i*num_ops_per_thread, (i+1)*num_ops_per_thread - 1)
 
47
 
 
48
        puts "Thread #{i} done"
 
49
      }
 
50
    }
 
51
    threads.each {|t|
 
52
      t.join
 
53
    }
 
54
  end
 
55
 
 
56
  #to reverse a range of String elements in @array.
 
57
  def reverse_strings(beginIndex, endIndex)
 
58
    while beginIndex <= endIndex
 
59
      puts "another 10 in #{Thread.current.inspect}" if beginIndex % 10 == 0
 
60
      reverse_string(@array[beginIndex])
 
61
      beginIndex += 1
 
62
    end
 
63
  end
 
64
 
 
65
  def run(argument)
 
66
    count = argument.to_i
 
67
    @num_threads = count
 
68
 
 
69
    t = Time.now
 
70
    do_test()
 
71
    puts "Time: #{Time.now - t}"
 
72
  end
 
73
 
 
74
end
 
75
 
 
76
5.times {
 
77
  ThreadScalability.new.run(ARGV[0].to_i)
 
78
}