Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A simple sample of apply this threadpool #113

Open
lix19937 opened this issue Apr 29, 2024 · 1 comment
Open

A simple sample of apply this threadpool #113

lix19937 opened this issue Apr 29, 2024 · 1 comment

Comments

@lix19937
Copy link

lix19937 commented Apr 29, 2024

#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
Copy link
Author

#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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant