Use template to get lambda for RAII

This commit is contained in:
topjohnwu 2020-04-30 01:27:36 -07:00
parent 5fd574a14f
commit 947e3b06b4
2 changed files with 11 additions and 14 deletions

View File

@ -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<void()> &&fn) {
return new_daemon_thread(proxy_routine, new std::function<void()>(std::move(fn)));
int new_daemon_thread(std::function<void()> &&entry) {
return new_daemon_thread(proxy_routine, new std::function<void()>(std::move(entry)));
}
static char *argv0;

View File

@ -29,16 +29,13 @@ private:
pthread_mutex_t *mutex;
};
template <class Func>
class run_finally {
public:
explicit run_finally(std::function<void()> &&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<void()> fn;
const Func &fn;
};
template <typename T>
@ -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<void()> &&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<void()> &&entry);
struct exec_t {
bool err = false;