test_Thread.cpp 2.4 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 16 17 18 19 20 21 22

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 <atomic>
#include <paddle/utils/Thread.h>
#include <gtest/gtest.h>

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;
55 56 57 58 59 60 61 62 63 64
  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 已提交
65 66 67 68 69 70 71 72
      });
  levelOnePool.addBatchJobs(moniterJobs);
  ASSERT_EQ(counter, numMonitors * numSlaves);
}

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

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

  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();
}