简体   繁体   English

boost.asio和查询数据库

[英]boost.asio and queries to the database

I am writing a network application in C++ using boost.asio. 我正在使用boost.asio用C ++编写网络应用程序。

I need to do three things: 我需要做三件事:

  1. make a connection from a client 与客户建立联系
  2. make a request to the database 向数据库发出请求
  3. return the result to the client. 将结果返回给客户端。

All operations except 2 are nonblocking. 除2外的所有操作都是非阻塞的。 But during the database query all of the application is blocked and non-performing other customers. 但是,在数据库查询期间,所有应用程序均被阻止,从而使其他客户无法正常运行。

How can I be in this situation? 在这种情况下我该怎么办?

As you haven't provided a detailed description of your case I assume, that you'd like to process connections from clients in many concurent threads. 因为您没有提供详细的案例描述,所以我认为您想在许多并发线程中处理来自客户端的连接。 Connection handlers are run in thread, that called io_service::run() . 连接处理程序在线程中运行,该线程称为io_service::run()

You can create a pool of threads processing connection handlers (and waiting for finalizing database connection), by running io_service::run() from multiple threads. 您可以通过从多个线程运行io_service::run()来创建处理连接处理程序(并等待数据库连接完成)的线程池。 See Boost.Asio docs . 参见Boost.Asio文档

Unfortunately, there are many external libraries that do not offer asynchronous interfaces. 不幸的是,有许多外部库不提供异步接口。 This happens most often when the library attempts to abstract away some important aspect of how it works. 当库试图抽象出其工作方式的一些重要方面时,通常会发生这种情况。 In this case, the database interface abstraction is leaking the fact that it blocks on a network request by blocking your thread. 在这种情况下,数据库接口抽象通过阻塞线程来泄漏它在网络请求上阻塞的事实。

Unless your database provider offers an asynchronous interface (I doubt it, never seen one that did), you will have to live with the fact that this blocks. 除非您的数据库提供者提供了一个异步接口(我对此表示怀疑,但从未见过这样的接口),否则您将不得不忍受这一事实。 You basically have to consider it almost equal to a task that runs a CPU-intensive computation with respect to completion. 基本上,您必须考虑到它几乎等同于就完成而言运行CPU密集型计算的任务。

You will need to either spawn an additional thread to make the request without blocking the asynchronous I/O completion handler or move this work to another process and have that process block on the database queries instead. 您将需要产生一个额外的线程来发出请求,而又不会阻塞异步I / O完成处理程序, 或者将这项工作移至另一个进程,并使该进程阻塞数据库查询。 This is common design in web servers, where the gateway just forwards I/O to an application server which then does its work in a synchronous fashion without blocking the gateway. 这是Web服务器中的常见设计,其中网关仅将I / O转发到应用程序服务器,然后该应用程序服务器以同步方式完成其工作而不会阻塞网关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM