op_repository.h 2.0 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#include <string>
W
wangguibao 已提交
17
#include "predictor/common/inner_common.h"
W
wangguibao 已提交
18 19 20 21 22

namespace baidu {
namespace paddle_serving {
namespace predictor {

W
wangguibao 已提交
23 24 25
#define REGISTER_OP(op)                                                       \
  ::baidu::paddle_serving::predictor::OpRepository::instance().regist_op<op>( \
      #op)
W
wangguibao 已提交
26 27 28 29

class Op;

class Factory {
W
wangguibao 已提交
30 31 32
 public:
  virtual Op* get_op() = 0;
  virtual void return_op(Op* op) = 0;
W
wangguibao 已提交
33 34
};

W
wangguibao 已提交
35
template <typename OP_TYPE>
W
wangguibao 已提交
36
class OpFactory : public Factory {
W
wangguibao 已提交
37 38 39 40 41 42 43 44 45 46 47
 public:
  Op* get_op() { return butil::get_object<OP_TYPE>(); }

  void return_op(Op* op) {
    butil::return_object<OP_TYPE>(dynamic_cast<OP_TYPE*>(op));
  }

  static OpFactory<OP_TYPE>& instance() {
    static OpFactory<OP_TYPE> ins;
    return ins;
  }
W
wangguibao 已提交
48 49 50
};

class OpRepository {
W
wangguibao 已提交
51 52
 public:
  typedef boost::unordered_map<std::string, Factory*> ManagerMap;
W
wangguibao 已提交
53

W
wangguibao 已提交
54 55
  OpRepository() {}
  ~OpRepository() {}
W
wangguibao 已提交
56

W
wangguibao 已提交
57 58 59 60
  static OpRepository& instance() {
    static OpRepository repo;
    return repo;
  }
W
wangguibao 已提交
61

W
wangguibao 已提交
62 63 64
  template <typename OP_TYPE>
  void regist_op(std::string op_type) {
    _repository[op_type] = &OpFactory<OP_TYPE>::instance();
W
wangguibao 已提交
65
    RAW_LOG_INFO("Succ regist op: %s", op_type.c_str());
W
wangguibao 已提交
66
  }
W
wangguibao 已提交
67

W
wangguibao 已提交
68
  Op* get_op(std::string op_type);
W
wangguibao 已提交
69

W
wangguibao 已提交
70
  void return_op(Op* op);
W
wangguibao 已提交
71

W
wangguibao 已提交
72
  void return_op(const std::string& op_type, Op* op);
W
wangguibao 已提交
73

W
wangguibao 已提交
74 75
 private:
  ManagerMap _repository;
W
wangguibao 已提交
76 77
};

W
wangguibao 已提交
78 79 80
}  // namespace predictor
}  // namespace paddle_serving
}  // namespace baidu