progschj / ThreadPool

A simple C++11 Thread Pool implementation
zlib License
7.63k stars 2.21k forks source link

A simple sample of apply this threadpool #113

Open lix19937 opened 2 months ago

lix19937 commented 2 months ago

#include <iostream>
#include "ThreadPool.h"

class MyT {
 public:
  int run(int i) { return i; }
  int init() { return 0; }
};

class MyClass {
  void loopDoSomething() {}
  void sayHello() { std::thread t(&MyClass::loopDoSomething, this); }
};

int main() {
  ThreadPool pool(4);
  MyT myt;

  for (int i = 0; i < 6; ++i) {
    // enqueue and store future
    auto result = pool.enqueue([](int answer) { return answer; }, 42);

    auto result2 = pool.enqueue(&MyT::run, &myt, i);

    // get result from future
    std::cout << result.get() << std::endl;
    std::cout << result2.get() << std::endl;

    std::cout << "\n" << std::endl;
  }

  return 0;
}

  // if (0) {
  //   WorkFlow wf;
  //   __LOG_DEBUG("%p ", &wf);
  //   wf.Init(cfgs[0]);
  //   __LOG_DEBUG("%p ", &wf);
  //   std::thread t1(&WorkFlow::Run, &wf, &runtime_tensor, 1);
  //   t1.join();
  // }
lix19937 commented 2 months ago

#include <iostream>
#include <vector>
#include <chrono>
#include "ThreadPool.h"

std::vector<std::vector<int>> a;

int main()
{
  ThreadPool pool(10);

  // create a <future> vector to wait the output
  std::vector<std::future<std::vector<int>>> results;
  std::vector<int> batch = {3, 3, 3};
  int m = 3;

  for (int b = 0; b < batch.size(); b++)
  {
    if (m > 0)
    {
      batch.push_back(4);
    }
    for (int i = 0; i < batch[b]; i++)
    {
      results.emplace_back(
          pool.enqueue([i]
                       {
                    std::vector<int> res = {i}; 
                    std::cout << "hello " << i << " ";
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                    std::cout << "world " << i << " ";
                    return res; }));
    }
    m--;
  }

  // get output
  for (auto &&result : results)
    a.emplace_back(result.get());
  std::cout << std::endl;

  // after get all output, print it
  for (int i = 0; i < a.size(); i++)
  {
    for (int j = 0; j < a[i].size(); j++)
      std::cout << a[i][j] << " ";
  }

  system("pause");
  return 0;
}