bsf-inl.h 6.2 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

W
wangguibao 已提交
15 16
#pragma once

W
wangguibao 已提交
17
#include <butil/atomicops.h>
W
wangguibao 已提交
18 19
#include <sys/syscall.h>
#include <boost/bind.hpp>
W
wangguibao 已提交
20 21 22 23 24 25

#include "common/inner_common.h"

namespace im {
namespace bsf {

W
wangguibao 已提交
26
template <typename TaskT>
W
wangguibao 已提交
27
void* TaskExecutor<TaskT>::thread_entry(void* args) {
W
wangguibao 已提交
28 29 30 31
  ThreadContext<TaskT>* context = static_cast<ThreadContext<TaskT>*>(args);
  TaskExecutor<TaskT>* executor =
      static_cast<TaskExecutor<TaskT>*>(context->executor);
  executor->work(context);
W
wangguibao 已提交
32

W
wangguibao 已提交
33
  return NULL;
W
wangguibao 已提交
34 35
}

W
wangguibao 已提交
36
template <typename TaskT>
W
wangguibao 已提交
37
int TaskExecutor<TaskT>::start(uint32_t thread_num, uint32_t init_timeout_sec) {
W
wangguibao 已提交
38 39 40 41 42
  _stop = false;
  if (!_thread_contexts.empty()) {
    LOG(WARNING) << "BSF has started";
    return 0;
  }
W
wangguibao 已提交
43

W
wangguibao 已提交
44 45 46 47
  if (thread_num == 0) {
    LOG(ERROR) << "cannot init BSF with zero thread";
    return -1;
  }
W
wangguibao 已提交
48

W
wangguibao 已提交
49 50 51 52 53
  ThreadContext<TaskT>* contexts = new ThreadContext<TaskT>[thread_num];
  for (uint32_t i = 0; i < thread_num; ++i) {
    contexts[i].executor = this;
    if (_user_thread_contexts != NULL) {
      contexts[i].user_thread_context = _user_thread_contexts[i];
W
wangguibao 已提交
54 55
    }

W
wangguibao 已提交
56 57 58 59 60 61 62
    int rc = THREAD_CREATE(
        &contexts[i].tid, NULL, &TaskExecutor::thread_entry, &contexts[i]);
    if (rc != 0) {
      LOG(ERROR) << "failed to create BSF worker thread: index=" << i
                 << ", rc=" << rc << ", errno=" << errno << ":"
                 << strerror(errno);
      return -1;
W
wangguibao 已提交
63 64
    }

W
wangguibao 已提交
65 66
    _thread_contexts.push_back(&contexts[i]);
  }
W
wangguibao 已提交
67

W
wangguibao 已提交
68 69
  int init_timeout = init_timeout_sec * 1000 * 1000;
  bool has_error = false;
W
wangguibao 已提交
70

W
wangguibao 已提交
71 72 73 74
  bool has_timeout = true;
  if (init_timeout == 0) {
    has_timeout = false;
  }
W
wangguibao 已提交
75

W
wangguibao 已提交
76 77
  while (!has_timeout || init_timeout > 0) {
    bool done = true;
W
wangguibao 已提交
78
    for (size_t i = 0; i < _thread_contexts.size(); ++i) {
W
wangguibao 已提交
79 80 81 82
      if (_thread_contexts[i]->init_status < 0) {
        has_error = true;
        break;
      }
W
wangguibao 已提交
83

W
wangguibao 已提交
84 85 86
      if (_thread_contexts[i]->init_status == 0) {
        done = false;
      }
W
wangguibao 已提交
87 88
    }

W
wangguibao 已提交
89 90 91
    if (has_error) {
      LOG(ERROR) << "BSF thread init error";
      return -1;
W
wangguibao 已提交
92 93
    }

W
wangguibao 已提交
94 95 96
    if (done) {
      LOG(INFO) << "BSF thread init done";
      return 0;
W
wangguibao 已提交
97 98
    }

W
wangguibao 已提交
99 100 101 102 103
    // 100ms
    const int sleep_interval = 100 * 1000;
    usleep(sleep_interval);
    init_timeout -= sleep_interval;
  }
W
wangguibao 已提交
104

W
wangguibao 已提交
105 106 107
  LOG(ERROR) << "BSF thread init timed out";
  return -1;
}
W
wangguibao 已提交
108

W
wangguibao 已提交
109 110 111 112 113 114 115 116 117 118 119 120
template <typename TaskT>
void TaskExecutor<TaskT>::stop() {
  _stop = true;
  for (size_t i = 0; i < _thread_contexts.size(); ++i) {
    THREAD_CANCEL(_thread_contexts[i]->tid);
  }

  for (size_t i = 0; i < _thread_contexts.size(); ++i) {
    THREAD_JOIN(_thread_contexts[i]->tid, NULL);
  }
  _thread_contexts.clear();
}
W
wangguibao 已提交
121

W
wangguibao 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
template <typename TaskT>
TaskHandler<TaskT> TaskExecutor<TaskT>::schedule(const InArrayT& in,
                                                 OutArrayT& out) {  // NOLINT
  TaskT* task = butil::get_object<TaskT>();
  if (!task) {
    LOG(ERROR) << "Failed get TaskT from object pool";
    return TaskHandler<TaskT>::valid_handle();
  }

  if (!BatchTasks<TaskT>::check_valid(in, out, _batch_align)) {
    LOG(ERROR) << "Invalid input & output";
    return TaskHandler<TaskT>::valid_handle();
  }

  int fds[2];
  int rc = pipe(fds);
  if (rc != 0) {
    LOG(ERROR) << "call pipe() failed, errno=" << errno << ":"
               << strerror(errno);
    return TaskHandler<TaskT>::valid_handle();
  }

  task->read_fd = fds[0];
  task->write_fd = fds[1];
  task->owner_tid = ::syscall(SYS_gettid);

  task->in = &in;
  task->out = &out;
  task->rem = in.size();
  task->size = in.size();
  task->index.store(0, butil::memory_order_relaxed);

  AutoMutex lock(_mut);
  _task_queue.push_back(task);
  THREAD_COND_SIGNAL(&_cond);

  return TaskHandler<TaskT>(*task);
W
wangguibao 已提交
159 160
}

W
wangguibao 已提交
161 162 163 164 165 166
template <typename TaskT>
bool TaskExecutor<TaskT>::fetch_batch(BatchTasks<TaskT>& batch) {  // NOLINT
  AutoMutex lock(_mut);
  while (_task_queue.empty()) {
    THREAD_COND_WAIT(&_cond, &_mut);
  }
W
wangguibao 已提交
167

W
wangguibao 已提交
168 169 170 171
  if (_task_queue.empty()) {
    LOG(ERROR) << "invalid task queue!";
    return false;
  }
W
wangguibao 已提交
172

W
wangguibao 已提交
173 174 175 176 177
  while (!_task_queue.empty()) {
    TaskT* task = _task_queue.front();
    size_t rem = batch.append_task(task);
    if (task->rem <= 0) {
      _task_queue.pop_front();
W
wangguibao 已提交
178
    }
W
wangguibao 已提交
179 180
    if (rem <= 0) break;
  }
W
wangguibao 已提交
181

W
wangguibao 已提交
182
  return true;
W
wangguibao 已提交
183 184
}

W
wangguibao 已提交
185
template <typename TaskT>
W
wangguibao 已提交
186
int TaskExecutor<TaskT>::work(ThreadContext<TaskT>* context) {
W
wangguibao 已提交
187 188 189 190 191 192 193
  if (_thread_init_fn != NULL) {
    if (_thread_init_fn(context->user_thread_context) != 0) {
      LOG(ERROR) << "execute thread init thunk failed, BSF thread will exit";
      context->init_status = -1;
      return -1;
    } else {
      LOG(INFO) << "execute thread init thunk succeed";
W
wangguibao 已提交
194
    }
W
wangguibao 已提交
195
  }
W
wangguibao 已提交
196

W
wangguibao 已提交
197 198 199 200 201 202
  context->init_status = 1;
  while (!_stop) {
    if (_thread_reset_fn != NULL) {
      if (_thread_reset_fn(context->user_thread_context) != 0) {
        LOG(ERROR) << "execute user thread reset failed";
      }
W
wangguibao 已提交
203 204
    }

W
wangguibao 已提交
205 206 207 208 209 210 211 212 213
    BatchTasks<TaskT> batch(_batch_size, _batch_align);
    if (fetch_batch(batch)) {
      batch.merge_tasks();
      _fn(batch.in(), batch.out());
      batch.notify_tasks();
    }
  }

  return 0;
W
wangguibao 已提交
214 215
}

W
wangguibao 已提交
216 217 218 219
template <typename InItemT, typename OutItemT>
bool TaskManager<InItemT, OutItemT>::schedule(const InArrayT& in,
                                              OutArrayT& out) {  // NOLINT
  TaskHandler<TaskT> handler = _executor.schedule(in, out);
W
wangguibao 已提交
220

W
wangguibao 已提交
221 222 223 224 225 226 227
  if (handler.valid()) {
    _task_owned = handler;
    return true;
  } else {
    LOG(ERROR) << "failed to schedule task";
    return false;
  }
W
wangguibao 已提交
228 229
}

W
wangguibao 已提交
230
template <typename InItemT, typename OutItemT>
W
wangguibao 已提交
231
void TaskManager<InItemT, OutItemT>::wait() {
W
wangguibao 已提交
232 233 234 235
  char buffer[128];
  while (read(_task_owned.read_fd, buffer, sizeof(buffer)) < 0 &&
         errno == EINTR) {
  }
W
wangguibao 已提交
236

W
wangguibao 已提交
237 238
  close(_task_owned.read_fd);
  close(_task_owned.write_fd);
W
wangguibao 已提交
239

W
wangguibao 已提交
240 241 242
  _task_owned.read_fd = -1;
  _task_owned.write_fd = -1;
  return;
W
wangguibao 已提交
243
}
W
wangguibao 已提交
244 245
}  // namespace bsf
}  // namespace im