Boost.Asio 异步 TCP 客户端和多线程
我的应用程序是一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,在这种情况下(一般情况下)您不需要锁定它。这些事件只能从运行 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.
如果您由于共享资源或其他原因需要某种锁定,您应该查看 股。
If you would need some sort of locking because of shared resources or whatever, you should have a look at strands.