ตัวอย่าง Thread เล็กน้อย

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

ต่อเนื่องจาก topic ของฝั่ง python
มาดูตัวอย่าง Thread ขำๆ ของ Ruby สักนิด

class Cal
  attr_accessor :num
  def initialize
      @num = 0
  end
  def add
      @num += 1
  end
end
 
cal = Cal.new
100000.times { cal.add }
100000.times { cal.add }
puts "#{cal.num}"  # => 200000
 
cal.num= 0
thread1 = Thread.new { 100000.times { cal.add } }
thread2 = Thread.new { 100000.times { cal.add } }
 
puts "#{cal.num}"  # => 110541 ??  

ทีนี้น่าจะพอเข้าใจเรื่อง Thread มากขึ้น พร้อมรู้ปัญหาถ้าเราไม่ใช้ mutex มาป้องกันว่าจะเกิดเหตุการณ์อะไรขี้น

ป.ล. อยากเห็น code monitor จัง

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น