Boost.Asio 异步 TCP 客户端和多线程

发布于 2024-10-06 11:24:06 字数 260 浏览 0 评论 0原文

我的应用程序是一个 TCP 客户端,非常类似于 Boost.Asio 聊天客户端示例

我添加了几个调用 chat_client::write 的单独线程。这是否意味着我必须为 do_write 或 handle_write 添加锁定机制?有什么推荐的方法吗?

My application is a TCP client that closely resembles the Boost.Asio chat client example.

I'm adding a few separate threads that call chat_client::write. Does this mean I would have to add a locking mechanism to do_write or handle_write? is there any recommended method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风透绣罗衣 2024-10-13 11:24:06

不,在这种情况下(一般情况下)您不需要锁定它。这些事件只能从运行 io_service 的线程中处理。如果只有一个,则不需要锁定。 post() 将新消息发送到 io_service 对于多个调用线程来说已经是线程安全的。

在您的特定示例中,您可能希望按值而不是按引用获取 chat_message,或者在 io_service 线程中使用它之前,它可能会超出 post()'ing 线程的范围。

No, you do not need to lock it in that case (in general). The events will only be handled from threads that have an io_service running. If that is only one, no locking is required. post()'ing new messages to an io_service is already thread-safe from multiple calling threads.

In your specific example, you might want to take the chat_message by-value instead of by-reference, or it might go out of scope in the post()'ing thread before being used in the io_service thread.

薯片软お妹 2024-10-13 11:24:06

如果您由于共享资源或其他原因需要某种锁定,您应该查看

If you would need some sort of locking because of shared resources or whatever, you should have a look at strands.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文