boost asio thread_group only run one thread

Viewed 72

I am studing boost library. I want to use fiber with blocking api so I try to use a thread pool to run blocking api. When the blocking api is finished, the fiber get the result. I have created a thread pool of 4 threads, but I found that only one thread is running. Why? Here is my code.

#include <boost/asio.hpp>
#include <boost/fiber/all.hpp>
#include <boost/fiber/fiber.hpp>
#include <boost/fiber/future/future.hpp>
#include <boost/fiber/future/promise.hpp>
#include <boost/fiber/operations.hpp>
#include <chrono>
#include <ctime>
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>

using namespace std;
using namespace boost;

time_t block_api() {
  std::this_thread::sleep_for(std::chrono::seconds(1));
  return clock();
}

class AsyncWrapper {
public:
  AsyncWrapper(asio::thread_pool &pool) : pool_(&pool) {}
  ~AsyncWrapper() {}

  time_t async_api() {
    fibers::promise<time_t> promise;
    boost::fibers::future<time_t> future(promise.get_future());

    auto func = [&]() mutable {
      auto ret = block_api();
      std::cout << "run on:"<<getpid()<<std::endl;
      promise.set_value(ret);
    };

    asio::post(pool_->get_executor(), func);
    return future.get();
  }

private:
  asio::thread_pool *pool_ = nullptr;
};

static asio::thread_pool g_pool(4);

int main(int argc, char **argv) {
  if (argc != 2) {
    return -1;
  }
  std::string arg = argv[1];
  std::cout << "press enter to start" << std::endl;
  getchar();
  for (int32_t i = 0; i < stoi(arg); i++) {
    fibers::fiber f([]() {
      AsyncWrapper async_wrapper(g_pool);
      auto ret = async_wrapper.async_api();
    });
    f.detach();
  }

  this_fiber::yield();
  return 0;
}

When I use command to analysis my program ,I saw that

top - 17:32:03 up  5:29,  0 users,  load average: 0.19, 0.17, 0.20
Threads:   5 total,   1 running,   4 sleeping,   0 stopped,   0 zombie
%Cpu(s):  8.3 us,  0.0 sy,  0.0 ni, 91.6 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
MiB Mem :   7931.7 total,   5037.4 free,   2405.4 used,    488.9 buff/cache
MiB Swap:   2048.0 total,   1259.0 free,    789.0 used.   5229.7 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
10338 wuhaotao  20   0  431880  15732   3424 R  99.7   0.2   0:03.63 with_blocking_a
10339 wuhaotao  20   0  431880  15732   3424 S   0.0   0.2   0:00.00 with_blocking_a
10340 wuhaotao  20   0  431880  15732   3424 S   0.0   0.2   0:00.00 with_blocking_a
10341 wuhaotao  20   0  431880  15732   3424 S   0.0   0.2   0:00.00 with_blocking_a
10342 wuhaotao  20   0  431880  15732   3424 S   0.0   0.2   0:00.00 with_blocking_a

Only the 10338 thread is running......

0 Answers
Related