Skip to content

Instantly share code, notes, and snippets.

@xuanyu-h
Created November 1, 2018 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuanyu-h/df330aada2e5253e525b8112341db1ab to your computer and use it in GitHub Desktop.
Save xuanyu-h/df330aada2e5253e525b8112341db1ab to your computer and use it in GitHub Desktop.
synchronizing access to an object
# encoding: utf-8
# frozen_string_literal: true
require 'thwait'
class Object
def synchronize
mutex.synchronize { yield self }
end
def mutex
@mutex ||= Mutex.new
end
end
list = []
thread_1 = Thread.new { list.synchronize { |l| sleep(1); 3.times { l.push "Thread 1" } } }
thread_2 = Thread.new { list.synchronize { |l| 3.times { l.push "Thread 2" } } }
thread_1.join
thread_2.join
p list # ["Thread 1", "Thread 1", "Thread 1", "Thread 2", "Thread 2", "Thread 2"]
list = []
thread_1 = Thread.new { sleep(3); 3.times { list.push "Thread 1" } }
thread_2 = Thread.new { 3.times { list.push "Thread 2" } }
thread_1.join
thread_2.join
p list # ["Thread 2", "Thread 2", "Thread 2", "Thread 1", "Thread 1", "Thread 1"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment