I created a console application that sends data on a network link. I used the boost library, both the thread and the asio ones; currently i’m running it under Windows. If I run a single application it works perfectly, but if I open two instances on two different consoles, the CPU load goes to 100%, if I close one of the application it goes back to normal. I just used a simple socket with async reads and writes, and threads with condition variables and mutexes. Is there any special thingh to do when dealing with such a situation? I can show you some code, but I think it’s nothing special:
socket->connect(tcp::endpoint(address::from_string(getAddress()),getPort()));
for connecting
and
socket->async_read_some(buffer(receiveData),bind(&NetworkLink::handle_response, this,placeholders::error,placeholders::bytes_transferred));
inside the handle_response function for async reading.
For the thread I use
boost::unique_lock<boost::mutex> messages_lock(message_received_mutex);
Before deleting everything and starting a simple test project from scratch I would like to know if there are any special care to be taken in this situation.
Ok it seems I’ve tracked down the problem. First of all, the 100% CPU usage was due to the fact that each instance was using 50% of the CPU (I’m on a dual core PC). So I run all over the code and found out this. I had this in my code, inside the NetworkLink::handle_response function:
I used the io_service.run(); because before the software was not receiving data. Now I removed the line, I don’t get the 50% CPU usage, but the handler response is not called so I cannot receive any data. Any thought about this?
Thanks
PS: I created a small app that shows this problem:
If you remove the comment from th line
// cout << bytes_transferred << ‘ ‘;
in the handle response functionyou get a lower CPU usage, I guess because of the delay for writing to the screen.