OSDN Git Service

Add thread_is_self function
authorSharvil Nanavati <sharvil@google.com>
Thu, 14 Aug 2014 19:36:39 +0000 (12:36 -0700)
committerAndre Eisenbach <eisenbach@google.com>
Mon, 16 Mar 2015 23:51:28 +0000 (16:51 -0700)
This is useful to compare the current thread against another one.

osi/include/thread.h
osi/src/thread.c
osi/test/thread_test.cpp

index 03ccbde..5b9eb04 100644 (file)
@@ -18,6 +18,8 @@
 
 #pragma once
 
+#include <stdbool.h>
+
 #define THREAD_NAME_MAX 16
 
 typedef struct reactor_t reactor_t;
@@ -51,6 +53,10 @@ bool thread_post(thread_t *thread, thread_fn func, void *context);
 // |thread| may not be NULL.
 void thread_stop(thread_t *thread);
 
+// Returns true if the current thread is the same as the one represented by |thread|.
+// |thread| may not be NULL.
+bool thread_is_self(const thread_t *thread);
+
 // Returns the name of the given |thread|. |thread| may not be NULL.
 const char *thread_name(const thread_t *thread);
 
index 96b8679..daa6423 100644 (file)
@@ -152,6 +152,11 @@ void thread_stop(thread_t *thread) {
   reactor_stop(thread->reactor);
 }
 
+bool thread_is_self(const thread_t *thread) {
+  assert(thread != NULL);
+  return !!pthread_equal(pthread_self(), thread->pthread);
+}
+
 reactor_t *thread_get_reactor(const thread_t *thread) {
   assert(thread != NULL);
   return thread->reactor;
index 30e1f3b..ea8e06c 100644 (file)
@@ -110,3 +110,20 @@ TEST(ThreadTest, test_unregister) {
   ASSERT_FALSE(FD_ISSET(wait_fd, &read_fds));
   thread_free(thread);
 }
+
+static void thread_is_self_fn(void *context) {
+  thread_t *thread = (thread_t *)context;
+  EXPECT_TRUE(thread_is_self(thread));
+}
+
+TEST(ThreadTest, test_thread_is_self) {
+  thread_t *thread = thread_new("test_thread");
+  thread_post(thread, thread_is_self_fn, thread);
+  thread_free(thread);
+}
+
+TEST(ThreadTest, test_thread_is_not_self) {
+  thread_t *thread = thread_new("test_thread");
+  EXPECT_FALSE(thread_is_self(thread));
+  thread_free(thread);
+}