简体   繁体   中英

Boost.Asio Asynchronous TCP client and multi-threading

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?

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.

如果由于共享资源或其他原因需要某种形式的锁定,则应该看看strands

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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