C++20 协同例程可以无阻塞地实现同步接口吗?
我正在编写一个 GRPC 服务,并尝试在 Asio 的帮助下使用异步方法。该服务调用具有同步方法的 C++ 库。该库中的代码使用的接口必须由库的用户实现。这些接口包含同步方法。
我希望通过使用对其他服务的异步 GRPC 调用来实现这些接口。我的挑战是我不知道如何在同步和异步世界之间实现适配器。这在 C++ 中可能吗?
在(我的)理论上,我希望这个协同例程适配器发送 GRCP 请求,然后线程应该继续执行其他协同例程——而不是阻塞——同时等待 GRPC 回复。收到回复后,同步方法调用将返回到库。这样我就可以只用一个线程来实现我的 GRPC 服务,而不必担心多线程问题。
在方法中使用 co_await 时,返回值反映了该方法的异步性质,因此在实现同步接口时我不能(直接)使用 co_await 。相反,我可以发布一个包含 co_wait 的 lambda,但随后我必须对 future(或类似的)进行阻塞等待,并且我的单线程服务陷入死锁。我一直在考虑使用 co_yield 并制作一种生成器,因为这些生成器的使用者似乎可以是同步的。
此致
I am writing a GRPC service and am trying to use the asynchronous methods with the help from Asio. The service calls into a C++ library that have synchronous methods. The code in that library uses interfaces that must be implemented by the user of the library. These interfaces contains synchronous methods.
I wish to implement these interfaces by using asynchronous GRPC calls to other services. My challenge is that I cannot see how I can implement an adaptor between the synchronous - and asynchronous world. Is this at all possible in C++?
In (my) theory I want this co-routine adaptor to send the GRCP request and then the thread should continue executing other co-routines - and not be blocking - while waiting for the GRPC reply. When the reply is received the synchronous method call is returned to the library. This way I would be able to implement my GRPC service with only one thread and I do not have to worry about multi-threading issues.
When using co_await in a method then the return value is reflecting the async nature of the method, so I cannot use co_await (directly) when implementing a synchronous interface. Instead I can post a lambda containing the co_wait, but then I have to do a blocking wait on a future (or similar) and my single threaded service is deadlocked. I have been thinking of using co_yield and make a type of generator since it seems to be that the consumer of these generators can be synchronous.
Best regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论