c++ - 使用多核提升协程

标签 c++ multicore boost-coroutine

我的 tcp 服务器是基于这个 boost coroutine server example .

每秒有很多请求,服务器有两个核心但只使用一个,在任务管理器的性能选项卡中它永远不会超过 50% cpu,并且一个核心总是空闲的: enter image description here

如何使 boost::coroutine 与多核协同工作?

我刚刚想出了一个解决方案,添加一个 thread_pool :

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include "thread_pool.h"
#include <iostream>

using boost::asio::ip::tcp;

class session : public std::enable_shared_from_this<session>
{
public:
  explicit session(tcp::socket socket) { }

  void go()
  {
      std::cout << "dead loop" << std::endl;
      while(1) {} // causes 100% cpu usage, just for test
  }
};

int main()
{
  try
  {

    boost::asio::io_service io_service;

    thread_pool pool(1000); // maximum 1000 threads

    boost::asio::spawn(io_service,
        [&](boost::asio::yield_context yield)
        {
          tcp::acceptor acceptor(io_service,
            tcp::endpoint(tcp::v4(), 80));

          for (;;)
          {
            boost::system::error_code ec;
            tcp::socket socket(io_service);
            acceptor.async_accept(socket, yield[ec]);
            if (!ec) {
                pool.enqueue([&] { // add this to pool
                    std::make_shared<session>(std::move(socket))->go();
                });
            }
          }
        });

    io_service.run();
  }
  catch (std::exception& e)
  {}

  return 0;
}

现在代码似乎在 telnet 127.0.0.1 80 两次后以 100% CPU 运行。

但是多核协程的常用方式是什么?

最佳答案

一个线程只在一个内核上运行,所以你必须创建多个具有独立协程的线程。 asio 已经包含了一些线程管理支持,因此您通常必须启动一些线程:

int main() {
  std::vector<std::thread> pool;
  try {
    boost::asio::io_service io_service;
    {
      for(auto threadCount = std::thread::hardware_concurrency();
          threadCount;--threadCount)
        pool.emplace_back([](auto io_s) {return io_s->run(); }, &io_service);
    }

    // Normal code
  } catch(std::exception &e) {}
  for(auto &thread : pool) 
    thread.join();
  return 0;
}

重要的是在每个线程上运行 io_service.run()。然后,在.async_accept之后,你可以调用

io_service.post(&session::go, std::make_shared<session>(std::move(socket)))

在池中某处运行 session 。

关于c++ - 使用多核提升协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35908507/

相关文章:

c++ - 非 POD 类型的复制构造函数和普通构造函数

c++ - 在协程执行之间强制休眠

c++ - 分析文件名格式的字符串

c++ - 如何使 QChar.unicode() 报告组合字符的 utf-16 表示形式?

c++ - 在 map 的 map 中查找值并返回主 map 的键(或替代键)

multithreading - 多核CPU共享MMU和页表吗?

c - 在 C 中用多个线程填充数组

visual-c++ - 对于 VisualC++ 开发,Intel i7(4 核,8 个基于 HT 的逻辑核心)是否比 Intel Core 2 Quad 更好?

c++ - boost 协程在 Windows x86_64 上不起作用吗?