| 2605 | } |
| 2606 | |
| 2607 | inline int SocketPool::GetSocket(SocketUniquePtr* ptr) { |
| 2608 | const int connection_pool_size = FLAGS_max_connection_pool_size; |
| 2609 | |
| 2610 | // In prev rev, SocketPool could be sharded into multiple SubSocketPools to |
| 2611 | // reduce thread contentions. The sharding key is mixed from pthread-id so |
| 2612 | // that data locality are better kept. |
| 2613 | // However sharding also makes the socket more frequently to be created |
| 2614 | // and closed, especially in real-world applications that one client |
| 2615 | // connects to many servers where one socket is lowly contended, different |
| 2616 | // threads accessing the socket may create pooled sockets in different sub |
| 2617 | // pools without reusing sockets left in other sub pools, which will |
| 2618 | // probably be closed by the CloseIdleConnections thread in socket_map.cpp, |
| 2619 | // resulting in frequent-create-and-close of connections. |
| 2620 | // Thus the sharding is merely a mechanism only meaningful in benchmarking |
| 2621 | // scenarios where one server is connected by one client with many threads. |
| 2622 | // Starting from r32203 the sharding capability is removed. |
| 2623 | |
| 2624 | SocketId sid = 0; |
| 2625 | if (connection_pool_size > 0) { |
| 2626 | for (;;) { |
| 2627 | { |
| 2628 | BAIDU_SCOPED_LOCK(_mutex); |
| 2629 | if (_pool.empty()) { |
| 2630 | break; |
| 2631 | } |
| 2632 | sid = _pool.back(); |
| 2633 | _pool.pop_back(); |
| 2634 | } |
| 2635 | _numfree.fetch_sub(1, butil::memory_order_relaxed); |
| 2636 | // Not address inside the lock since at most time the pooled socket |
| 2637 | // is likely to be valid. |
| 2638 | if (Socket::Address(sid, ptr) == 0) { |
| 2639 | _numinflight.fetch_add(1, butil::memory_order_relaxed); |
| 2640 | return 0; |
| 2641 | } |
| 2642 | } |
| 2643 | } |
| 2644 | // Not found in pool |
| 2645 | SocketOptions opt = _options; |
| 2646 | opt.health_check_interval_s = -1; |
| 2647 | if (get_client_side_messenger()->Create(opt, &sid) == 0 && |
| 2648 | Socket::Address(sid, ptr) == 0) { |
| 2649 | _numinflight.fetch_add(1, butil::memory_order_relaxed); |
| 2650 | return 0; |
| 2651 | } |
| 2652 | return -1; |
| 2653 | } |
| 2654 | |
| 2655 | inline void SocketPool::ReturnSocket(Socket* sock) { |
| 2656 | // NOTE: save the gflag which may be reloaded at any time. |