kshahar
kshahar

Reputation: 10513

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?

Upvotes: 0

Views: 3741

Answers (2)

André
André

Reputation: 470

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

Upvotes: 1

ltjax
ltjax

Reputation: 16007

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.

Upvotes: 2

Related Questions