-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathon_exit.h
49 lines (40 loc) · 1 KB
/
on_exit.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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() {
int ret = pthread_mutex_init(&lock_, NULL);
assert(ret == 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