summaryrefslogtreecommitdiffstats
path: root/src/include/on_exit.h
diff options
context:
space:
mode:
authorNoah Watkins <noahwatkins@gmail.com>2014-01-04 20:32:51 +0100
committerNoah Watkins <noahwatkins@gmail.com>2014-01-04 21:54:03 +0100
commit2181d25f7a07803227fc7ad0713ecf19b0507342 (patch)
tree2250500f86fbc40f8fae9f005eaae3819902e843 /src/include/on_exit.h
parentMerge pull request #1038 from ceph/wip-objectcacher-backoff (diff)
downloadceph-2181d25f7a07803227fc7ad0713ecf19b0507342.tar.xz
ceph-2181d25f7a07803227fc7ad0713ecf19b0507342.zip
onexit: add an on exit callback utility
Adds a class that executes registered callbacks in its destructor. Since static duration objects have their destructors called when returning from main or calling exit then this can be used as a replacement for on_exit. Signed-off-by: Noah Watkins <noahwatkins@gmail.com>
Diffstat (limited to 'src/include/on_exit.h')
-rw-r--r--src/include/on_exit.h48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/include/on_exit.h b/src/include/on_exit.h
new file mode 100644
index 00000000000..4bb8f2c0687
--- /dev/null
+++ b/src/include/on_exit.h
@@ -0,0 +1,48 @@
+#ifndef CEPH_ON_EXIT_H
+#define CEPH_ON_EXIT_H
+
+#include <pthread.h>
+#include <assert.h>
+#include <vector>
+
+/*
+ * Create a static instance at the file level to get callbacks called when the
+ * process exits via main() or exit().
+ */
+
+class OnExitManager {
+ public:
+ typedef void (*callback_t)(void *arg);
+
+ OnExitManager() {
+ assert(pthread_mutex_init(&lock_, NULL) == 0);
+ }
+
+ ~OnExitManager() {
+ pthread_mutex_lock(&lock_);
+ std::vector<struct cb>::iterator it;
+ for (it = funcs_.begin(); it != funcs_.end(); it++) {
+ it->func(it->arg);
+ }
+ funcs_.clear();
+ pthread_mutex_unlock(&lock_);
+ }
+
+ void add_callback(callback_t func, void *arg) {
+ pthread_mutex_lock(&lock_);
+ struct cb callback = { func, arg };
+ funcs_.push_back(callback);
+ pthread_mutex_unlock(&lock_);
+ }
+
+ private:
+ struct cb {
+ callback_t func;
+ void *arg;
+ };
+
+ std::vector<struct cb> funcs_;
+ pthread_mutex_t lock_;
+};
+
+#endif