From 8ce24cb92bc41e771c824cab601b29a7e8d37f67 Mon Sep 17 00:00:00 2001 From: liulanzheng Date: Wed, 29 May 2024 11:57:30 +0800 Subject: [PATCH] avoid duplicate construction for http dialer Signed-off-by: liulanzheng --- net/http/client.cpp | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/net/http/client.cpp b/net/http/client.cpp index e808b512..4823f109 100644 --- a/net/http/client.cpp +++ b/net/http/client.cpp @@ -41,21 +41,35 @@ class PooledDialer { std::unique_ptr tlssock; std::unique_ptr udssock; std::unique_ptr resolver; + bool initialized = false; + photon::mutex init_mtx; - //etsocket seems not support multi thread very well, use tcp_socket now. need to find out why - PooledDialer(TLSContext *_tls_ctx) : - tls_ctx(_tls_ctx ? _tls_ctx : new_tls_context(nullptr, nullptr, nullptr)), - tls_ctx_ownership(_tls_ctx == nullptr), - resolver(new_default_resolver(kDNSCacheLife)) { + PooledDialer() { + photon::fini_hook({this, &PooledDialer::at_photon_fini}); + } + + ~PooledDialer() { + } + + int init(TLSContext *_tls_ctx) { + if (initialized) + return 0; + SCOPED_LOCK(init_mtx); + if (initialized) + return 0; + tls_ctx = _tls_ctx; + if (!tls_ctx) { + tls_ctx_ownership = true; + tls_ctx = new_tls_context(nullptr, nullptr, nullptr); + } auto tcp_cli = new_tcp_socket_client(); auto tls_cli = new_tls_client(tls_ctx, new_tcp_socket_client(), true); tcpsock.reset(new_tcp_socket_pool(tcp_cli, -1, true)); tlssock.reset(new_tcp_socket_pool(tls_cli, -1, true)); udssock.reset(new_uds_client()); - photon::fini_hook({this, &PooledDialer::at_photon_fini}); - } - - ~PooledDialer() { + resolver.reset(new_default_resolver(kDNSCacheLife)); + initialized = true; + return 0; } void at_photon_fini() { @@ -145,7 +159,8 @@ class ClientImpl : public Client { } PooledDialer& get_dialer() { - thread_local PooledDialer dialer(m_tls_ctx); + thread_local PooledDialer dialer; + dialer.init(m_tls_ctx); return dialer; }