Skip to content

Instantly share code, notes, and snippets.

Created December 3, 2012 15:14
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 anonymous/4195632 to your computer and use it in GitHub Desktop.
Save anonymous/4195632 to your computer and use it in GitHub Desktop.
diff --git a/NEWS b/NEWS
index 41e836f..eec2848 100644
--- a/NEWS
+++ b/NEWS
@@ -93,6 +93,11 @@ with all sufficient information, see the ChangeLog file.
* Module#const_get accepts a qualified constant string, e.g.
Object.const_get("Foo::Bar::Baz")
+ * Mutex
+ * added method:
+ * added Mutex#owned? which returns the mutex is held by current
+ thread or not. [experimental]
+
* NilClass
* added method:
* added nil.to_h which returns {}
diff --git a/test/ruby/test_thread.rb b/test/ruby/test_thread.rb
index 145e021..d2bdd91 100644
--- a/test/ruby/test_thread.rb
+++ b/test/ruby/test_thread.rb
@@ -863,4 +863,31 @@ class TestThreadGroup < Test::Unit::TestCase
end
assert_in_delta(t1 - t0, 1, 1, bug5757)
end
+
+ def test_mutex_owned
+ mutex = Mutex.new
+
+ assert_equal(mutex.owned?, false)
+ mutex.synchronize {
+ assert_equal(mutex.owned?, true)
+ }
+ assert_equal(mutex.owned?, false)
+ end
+
+ def test_mutex_owned2
+ begin
+ mutex = Mutex.new
+ th = Thread.new {
+ mutex.lock
+ sleep
+ }
+
+ sleep 0.01 until th.status == "sleep"
+ assert_equal(mutex.locked?, true)
+ assert_equal(mutex.owned?, false)
+ ensure
+ th.kill if th
+ end
+ end
+
end
diff --git a/thread.c b/thread.c
index 4b1adc1..ecdf279 100644
--- a/thread.c
+++ b/thread.c
@@ -4151,6 +4151,28 @@ rb_mutex_lock(VALUE self)
return self;
}
+/*
+ * call-seq:
+ * mutex.owned? -> true or false
+ *
+ * Returns +true+ if this lock is currently held by current thread.
+ * <em>This API is experimental, and subject to change.</em>
+ */
+static VALUE
+rb_mutex_owned_p(VALUE self)
+{
+ VALUE owned = Qfalse;
+ rb_thread_t *th = GET_THREAD();
+ rb_mutex_t *mutex;
+
+ GetMutexPtr(self, mutex);
+
+ if (mutex->th == th)
+ owned = Qtrue;
+
+ return owned;
+}
+
static const char *
rb_mutex_unlock_th(rb_mutex_t *mutex, rb_thread_t volatile *th)
{
@@ -4733,6 +4755,7 @@ Init_Thread(void)
rb_define_method(rb_cMutex, "lock", rb_mutex_lock, 0);
rb_define_method(rb_cMutex, "unlock", rb_mutex_unlock, 0);
rb_define_method(rb_cMutex, "sleep", mutex_sleep, -1);
+ rb_define_method(rb_cMutex, "owned?", rb_mutex_owned_p, 0);
recursive_key = rb_intern("__recursive_key__");
rb_eThreadError = rb_define_class("ThreadError", rb_eStandardError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment