test_Thread.cpp 2.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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. */

#include <gtest/gtest.h>
Y
Yu Yang 已提交
16 17
#include <paddle/utils/Thread.h>
#include <atomic>
Z
zhangjinchao01 已提交
18 19 20 21 22

using paddle::AsyncThreadPool;  // NOLINT

TEST(AsyncThreadPool, addJob) {
  AsyncThreadPool pool(8);
23
  auto a = pool.addJob([] { return 1; });
Z
zhangjinchao01 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
  auto b = pool.addJob([] { return true; });
  auto c = pool.addJob([] { return false; });

  ASSERT_EQ(a.get(), 1);
  ASSERT_TRUE(b.get());
  ASSERT_FALSE(c.get());
}

TEST(AsyncThreadPool, addBatchJob) {
  AsyncThreadPool pool(8);
  std::atomic<int> counter{0};

  std::vector<AsyncThreadPool::JobFunc> jobs;

  for (int i = 0; i < 10000; i++) {
39
    jobs.emplace_back([&] { counter++; });
Z
zhangjinchao01 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  }

  pool.addBatchJobs(jobs);

  ASSERT_EQ(counter, 10000);
}

TEST(AsyncThreadPool, multiThreadAddBatchJob) {
  AsyncThreadPool levelOnePool(200);
  AsyncThreadPool levelTwoPool(200);

  std::shared_ptr<std::mutex> mut = std::make_shared<std::mutex>();
  int counter = 0;
  const int numMonitors = 300;
  const int numSlaves = 300;
Y
Yu Yang 已提交
55 56 57 58 59 60 61
  std::vector<AsyncThreadPool::JobFunc> moniterJobs(numMonitors, [&] {
    std::vector<AsyncThreadPool::JobFunc> slaveJobs(numSlaves, [mut, &counter] {
      std::lock_guard<std::mutex> lk(*mut);
      counter++;
    });
    levelTwoPool.addBatchJobs(slaveJobs);
  });
Z
zhangjinchao01 已提交
62 63 64 65 66 67 68
  levelOnePool.addBatchJobs(moniterJobs);
  ASSERT_EQ(counter, numMonitors * numSlaves);
}

TEST(AsyncThreadPool, addBatchJobWithResults) {
  AsyncThreadPool pool(100);

69
  std::vector<std::function<int()>> jobs;
Z
zhangjinchao01 已提交
70 71
  const int numJobs = 100;
  for (int i = 0; i < numJobs; i++) {
72
    jobs.emplace_back([i] { return i; });
Z
zhangjinchao01 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86
  }

  std::vector<int> res;
  pool.addBatchJobs(jobs, res);

  for (int i = 0; i < numJobs; i++) {
    ASSERT_EQ(res[i], i);
  }
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}