forked from hoong/ConfigServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatomic_operate.h
70 lines (53 loc) · 985 Bytes
/
atomic_operate.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#ifndef ATOMIC_OPERATE_H_
#define ATOMIC_OPERATE_H_
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <map>
struct OperateTask
{
virtual ~OperateTask(){}
virtual int run() = 0;
};
class AtomicOperate
{
class Operate
{
public:
int Process(OperateTask* t)
{
boost::mutex::scoped_lock lock(mutex_);
return t->run();
}
private:
boost::mutex mutex_;
};
public:
int operate(const std::string& k,OperateTask* t)
{
boost::shared_ptr<Operate> op;
std::map<std::string,boost::shared_ptr<Operate> >::iterator it;
it = opmap_.find(k);
if (it == opmap_.end())
{
boost::mutex::scoped_lock lock(mutex_);
op = boost::shared_ptr<Operate>(new Operate);
opmap_.insert(std::pair<std::string,boost::shared_ptr<Operate> >(k,op));
}
else
{
op = it->second;
}
if (op.get())
{
return op->Process(t);
}
else
{
return -1;
}
}
private:
boost::mutex mutex_;
std::map<std::string,boost::shared_ptr<Operate> > opmap_;
};
#endif