Skip to content

Commit d189f61

Browse files
authored
impl(spanner): lock mutex in total_sessions accessor (#15017)
1 parent 518d46a commit d189f61

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

google/cloud/spanner/internal/session_pool.cc

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -370,9 +370,13 @@ std::shared_ptr<SpannerStub> SessionPool::GetStub(Session const& session) {
370370
return GetStub(std::unique_lock<std::mutex>(mu_));
371371
}
372372

373-
void SessionPool::DecrementSessionCount(
374-
std::unique_lock<std::mutex> const&,
375-
google::cloud::spanner_internal::Session& session) {
373+
int SessionPool::total_sessions() const {
374+
std::lock_guard<std::mutex> lk(mu_);
375+
return total_sessions_;
376+
}
377+
378+
void SessionPool::DecrementSessionCount(std::unique_lock<std::mutex> const&,
379+
Session const& session) {
376380
--total_sessions_;
377381
auto const& channel = session.channel();
378382
if (channel) {

google/cloud/spanner/internal/session_pool.h

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,11 @@ class SessionPool : public std::enable_shared_from_this<SessionPool> {
118118
/**
119119
* Returns the number of sessions in the session pool plus the number of
120120
* sessions allocated to running transactions.
121+
*
122+
* @note This function should only be used for testing as other threads
123+
* could be modifying the underlying value immediately after it returns.
121124
*/
122-
int total_sessions() const { return total_sessions_; }
125+
int total_sessions() const;
123126

124127
private:
125128
friend std::shared_ptr<SessionPool> MakeSessionPool(
@@ -215,7 +218,7 @@ class SessionPool : public std::enable_shared_from_this<SessionPool> {
215218

216219
// Performs the necessary bookkeeping when a session is removed from use.
217220
void DecrementSessionCount(std::unique_lock<std::mutex> const& lk,
218-
Session& session);
221+
Session const& session);
219222

220223
spanner::Database const db_;
221224
google::cloud::CompletionQueue cq_;
@@ -226,7 +229,7 @@ class SessionPool : public std::enable_shared_from_this<SessionPool> {
226229
int const max_pool_size_;
227230
std::mt19937 random_generator_;
228231

229-
std::mutex mu_;
232+
mutable std::mutex mu_;
230233
std::condition_variable cond_;
231234
SessionHolder multiplexed_session_; // GUARDED_BY(mu_)
232235
std::vector<std::unique_ptr<Session>> sessions_; // GUARDED_BY(mu_)

0 commit comments

Comments
 (0)