Created
November 1, 2018 03:30
-
-
Save xuanyu-h/df330aada2e5253e525b8112341db1ab to your computer and use it in GitHub Desktop.
synchronizing access to an object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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