Skip to content

Commit 6ab917a

Browse files
Make send thread safe (#53)
1 parent 2cb0880 commit 6ab917a

File tree

1 file changed

+19
-20
lines changed

1 file changed

+19
-20
lines changed

include/cpp-statsd-client/StatsdClient.hpp

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,6 @@ class StatsdClient {
162162
//! The random number generator for handling sampling
163163
mutable std::mt19937 m_randomEngine;
164164

165-
//! The buffer string format our stats before sending them
166-
mutable std::string m_buffer;
167-
168165
//! Fixed floating point precision of gauges
169166
int m_gaugePrecision;
170167
};
@@ -196,8 +193,6 @@ inline StatsdClient::StatsdClient(const std::string& host,
196193
m_gaugePrecision(gaugePrecision) {
197194
// Initialize the random generator to be used for sampling
198195
seed();
199-
// Avoid re-allocations by reserving a generous buffer
200-
m_buffer.reserve(256);
201196
}
202197

203198
inline void StatsdClient::setConfig(const std::string& host,
@@ -291,35 +286,39 @@ inline void StatsdClient::send(const std::string& key,
291286
std::stringstream valueStream;
292287
valueStream << std::fixed << std::setprecision(m_gaugePrecision) << value;
293288

294-
m_buffer.clear();
289+
// the thread keeps this buffer around and reuses it, clear should be O(1)
290+
// and reserve should only have to do so the first time, after that, it's a no-op
291+
static thread_local std::string buffer;
292+
buffer.clear();
293+
buffer.reserve(256);
295294

296-
m_buffer.append(m_prefix);
295+
buffer.append(m_prefix);
297296
if (!m_prefix.empty() && !key.empty()) {
298-
m_buffer.push_back('.');
297+
buffer.push_back('.');
299298
}
300299

301-
m_buffer.append(key);
302-
m_buffer.push_back(':');
303-
m_buffer.append(valueStream.str());
304-
m_buffer.push_back('|');
305-
m_buffer.append(type);
300+
buffer.append(key);
301+
buffer.push_back(':');
302+
buffer.append(valueStream.str());
303+
buffer.push_back('|');
304+
buffer.append(type);
306305

307306
if (frequency < 1.f) {
308-
m_buffer.append("|@0.");
309-
m_buffer.append(std::to_string(static_cast<int>(frequency * 100)));
307+
buffer.append("|@0.");
308+
buffer.append(std::to_string(static_cast<int>(frequency * 100)));
310309
}
311310

312311
if (!tags.empty()) {
313-
m_buffer.append("|#");
312+
buffer.append("|#");
314313
for (const auto& tag : tags) {
315-
m_buffer.append(tag);
316-
m_buffer.push_back(',');
314+
buffer.append(tag);
315+
buffer.push_back(',');
317316
}
318-
m_buffer.pop_back();
317+
buffer.pop_back();
319318
}
320319

321320
// Send the message via the UDP sender
322-
m_sender->send(m_buffer);
321+
m_sender->send(buffer);
323322
}
324323

325324
inline void StatsdClient::seed(unsigned int seed) noexcept {

0 commit comments

Comments
 (0)