Skip to content

Asynchronous

Thread pool

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Chopping vegetables with a thread pool
#include <thread>

void vegetable_chopper(int vegetable_id) {
  printf("Thread %d chopped vegetable %d.\n", std::this_thread::get_id(),
        vegetable_id);
}

int main() {
  std::thread choppers[100];
  for (int i = 0; i < 100; i++) {
    choppers[i] = std::thread(vegetable_chopper, i);
  }
  for (auto& c : choppers) {
    c.join();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Chopping vegetables with a thread pool
#include <boost/asio.hpp>

void vegetable_chopper(int vegetable_id) {
  printf("Thread %d chopped vegetable %d.\n", std::this_thread::get_id(),
        vegetable_id);
}

int main() {
  boost::asio::thread_pool pool(4);  // 4 threads
  for (int i = 0; i < 100; i++) {
    boost::asio::post(pool, [i]() { vegetable_chopper(i); });
  }
  pool.join();
}