#include <cstdlib>#include <iostream>#include <boost/bind.hpp>#include <boost/smart_ptr.hpp>#include <asio.hpp>using asio::ip::tcp;const int max_threads = 32;typedef boost::shared_ptr<tcp::socket> socket_ptr;typedef boost::mutex::scoped_lock lock_t;struct shared_info_t { boost::condition ready, started; boost::mutex mutex; socket_ptr next_sock;};void worker(shared_info_t * info) { for (;;) { socket_ptr local_sock; // Wait for the shared slot to be filled { lock_t lock(info->mutex); while (!info->next_sock.get()) { ready.wait(lock); } // Make it mine // Leaves the shared slot with NULL local_sock.swap(info->next_sock); } // Tell the main thread that it can accept another connection started.notify_one(); // Run the session try { session(local_sock); } catch (asio::error& e) { std::cerr << "Error in thread: " << e << "\n"; } catch (std::exception& e) { std::cerr << "Exception in thread: " << e.what() << "\n"; } }}void server(asio::io_service& io_service, unsigned short port){ boost::thread_group tg; shared_info_t info; thread_count = max_threads; for (int i = 0; i < max_threads; i++) { tg.create_thread(boost::bind(worker, &info)); } tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port)); for (;;) { { // Wait until the shared slot is empty lock_t lock(info.mutex); while (info.next_sock.get()) { started.wait(lock); } // Put a new socket in the shared slot socket_ptr(new tcp::socket(io_service)).swap(info.next_sock); // Accept a connection a.accept(*local_sock); } // Notify a thread that the shared slot is ready ready.notify_one(); }}