@@ -183,7 +183,7 @@ void NeugDB::Close() {
183183 // closed flag update are atomic with respect to service registration,
184184 // so no rollback or re-check is needed and Close() stays idempotent.
185185 std::lock_guard<std::mutex> lock (service_mutex_);
186- if (HasActiveService () ) {
186+ if (active_service_ != nullptr ) {
187187 THROW_RUNTIME_ERROR (
188188 " Cannot close NeugDB while a NeugDBService is still associated "
189189 " with it. Stop and destroy the service first." );
@@ -227,14 +227,24 @@ void NeugDB::Close() {
227227}
228228
229229std::shared_ptr<Connection> NeugDB::Connect () {
230- if (HasActiveService ()) {
230+ std::lock_guard<std::mutex> lock (service_mutex_);
231+ if (IsClosed ()) {
232+ THROW_RUNTIME_ERROR (
233+ " Cannot create connection on a closed NeugDB instance." );
234+ }
235+ if (active_service_ != nullptr ) {
231236 THROW_RUNTIME_ERROR (
232237 " Cannot create connection while the database is being served by a "
233238 " NeugDBService." );
234239 }
235240 return connection_manager_->CreateConnection ();
236241}
237242
243+ bool NeugDB::HasActiveService () const {
244+ std::lock_guard<std::mutex> lock (service_mutex_);
245+ return active_service_ != nullptr ;
246+ }
247+
238248void NeugDB::RegisterService (NeugDBService* svc) {
239249 // Serialized with Close(): either the database is closed first (and this
240250 // registration is rejected), or the service registers first (and Close()
@@ -245,20 +255,22 @@ void NeugDB::RegisterService(NeugDBService* svc) {
245255 THROW_RUNTIME_ERROR (
246256 " Cannot register a NeugDBService on a closed NeugDB instance." );
247257 }
248- NeugDBService* expected = nullptr ;
249- if (!active_service_.compare_exchange_strong (expected, svc)) {
258+ if (active_service_ != nullptr ) {
250259 THROW_RUNTIME_ERROR (
251260 " NeugDB instance is already associated with a NeugDBService. Only "
252261 " one service instance is allowed per database." );
253262 }
263+ active_service_ = svc;
254264}
255265
256266void NeugDB::UnregisterService (NeugDBService* svc) {
257- NeugDBService* expected = svc ;
258- if (! active_service_. compare_exchange_strong (expected, nullptr ) ) {
267+ std::lock_guard<std::mutex> lock (service_mutex_) ;
268+ if (active_service_ != svc ) {
259269 LOG (WARNING ) << " UnregisterService: the given service is not the active "
260270 " service of this database." ;
271+ return ;
261272 }
273+ active_service_ = nullptr ;
262274}
263275
264276void NeugDB::RemoveConnection (std::shared_ptr<Connection> conn) {
0 commit comments