From 947e3b06b4318de06f5ff0fb1dc5c43713241db0 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 30 Apr 2020 01:27:36 -0700 Subject: [PATCH] Use template to get lambda for RAII --- native/jni/utils/misc.cpp | 8 ++++---- native/jni/utils/misc.hpp | 17 +++++++---------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/native/jni/utils/misc.cpp b/native/jni/utils/misc.cpp index b73894053..05dc3d5a2 100644 --- a/native/jni/utils/misc.cpp +++ b/native/jni/utils/misc.cpp @@ -126,9 +126,9 @@ int exec_command_sync(exec_t &exec) { return WEXITSTATUS(status); } -int new_daemon_thread(void *(*start_routine) (void *), void *arg, const pthread_attr_t *attr) { +int new_daemon_thread(thread_entry entry, void *arg, const pthread_attr_t *attr) { pthread_t thread; - int ret = xpthread_create(&thread, attr, start_routine, arg); + int ret = xpthread_create(&thread, attr, entry, arg); if (ret == 0) pthread_detach(thread); return ret; @@ -141,8 +141,8 @@ static void *proxy_routine(void *fp) { return nullptr; } -int new_daemon_thread(std::function &&fn) { - return new_daemon_thread(proxy_routine, new std::function(std::move(fn))); +int new_daemon_thread(std::function &&entry) { + return new_daemon_thread(proxy_routine, new std::function(std::move(entry))); } static char *argv0; diff --git a/native/jni/utils/misc.hpp b/native/jni/utils/misc.hpp index cd7537d1b..bbb2a427a 100644 --- a/native/jni/utils/misc.hpp +++ b/native/jni/utils/misc.hpp @@ -29,16 +29,13 @@ private: pthread_mutex_t *mutex; }; +template class run_finally { public: - explicit run_finally(std::function &&fn): fn(std::move(fn)) {} - - void disable() { fn = nullptr; } - - ~run_finally() { if (fn) fn(); } - + explicit run_finally(const Func &fn) : fn(fn) {} + ~run_finally() { fn(); } private: - std::function fn; + const Func &fn; }; template @@ -64,9 +61,9 @@ int parse_int(const char *s); static inline int parse_int(std::string s) { return parse_int(s.data()); } static inline int parse_int(std::string_view s) { return parse_int(s.data()); } -int new_daemon_thread(void *(*start_routine) (void *), void *arg = nullptr, - const pthread_attr_t *attr = nullptr); -int new_daemon_thread(std::function &&fn); +using thread_entry = void *(*)(void *); +int new_daemon_thread(thread_entry entry, void *arg = nullptr, const pthread_attr_t *attr = nullptr); +int new_daemon_thread(std::function &&entry); struct exec_t { bool err = false;