From 7c19f013b81edd43466ac88bf078cfdcf4ba534a Mon Sep 17 00:00:00 2001 From: Sharvil Nanavati Date: Thu, 14 Aug 2014 12:36:39 -0700 Subject: [PATCH] Add thread_is_self function This is useful to compare the current thread against another one. --- osi/include/thread.h | 6 ++++++ osi/src/thread.c | 5 +++++ osi/test/thread_test.cpp | 17 +++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/osi/include/thread.h b/osi/include/thread.h index 03ccbdec9..5b9eb049e 100644 --- a/osi/include/thread.h +++ b/osi/include/thread.h @@ -18,6 +18,8 @@ #pragma once +#include + #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); diff --git a/osi/src/thread.c b/osi/src/thread.c index 96b867952..daa642305 100644 --- a/osi/src/thread.c +++ b/osi/src/thread.c @@ -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; diff --git a/osi/test/thread_test.cpp b/osi/test/thread_test.cpp index 30e1f3bc2..ea8e06c7e 100644 --- a/osi/test/thread_test.cpp +++ b/osi/test/thread_test.cpp @@ -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); +} -- 2.11.0