Skip to content

Commit 6631382

Browse files
committed
Fix possible race condition in EventListener
1 parent 3f38f92 commit 6631382

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

src/fb-cpp/EventListener.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,11 @@ EventListener::EventListener(Attachment& attachment, const std::vector<std::stri
111111
&statusWrapper, &firebirdCallback, static_cast<unsigned>(eventBuffer.size()), eventBuffer.data()));
112112

113113
dispatcher = std::thread{&EventListener::dispatchLoop, this};
114+
115+
{ // scope
116+
std::unique_lock mutexGuard{mutex};
117+
condition.wait(mutexGuard, [this] { return initialized || !listening; });
118+
}
114119
}
115120

116121
bool EventListener::isListening() noexcept
@@ -186,6 +191,7 @@ void EventListener::handleEvent(unsigned length, const std::uint8_t* events)
186191
unsigned copyLength = 0;
187192
bool notify = false;
188193
bool shouldRequeue = false;
194+
bool notifyInitialized = false;
189195

190196
{ // scope
191197
std::lock_guard mutexGuard{mutex};
@@ -243,6 +249,7 @@ void EventListener::handleEvent(unsigned length, const std::uint8_t* events)
243249
if (listening)
244250
{
245251
listening = false;
252+
initialized = true;
246253
condition.notify_all();
247254
}
248255

@@ -267,6 +274,7 @@ void EventListener::handleEvent(unsigned length, const std::uint8_t* events)
267274
return;
268275

269276
listening = false;
277+
initialized = true;
270278
condition.notify_all();
271279
}
272280

@@ -282,8 +290,17 @@ void EventListener::handleEvent(unsigned length, const std::uint8_t* events)
282290
{
283291
previousHandle = std::move(eventsHandle);
284292
eventsHandle = std::move(newHandle);
293+
294+
if (!initialized)
295+
{
296+
initialized = true;
297+
notifyInitialized = true;
298+
}
285299
}
286300
}
301+
302+
if (notifyInitialized)
303+
condition.notify_all();
287304
}
288305
catch (...)
289306
{
@@ -296,6 +313,7 @@ void EventListener::handleEvent(unsigned length, const std::uint8_t* events)
296313
if (listening)
297314
{
298315
listening = false;
316+
initialized = true;
299317
condition.notify_all();
300318
}
301319
}

src/fb-cpp/EventListener.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ namespace fbcpp
168168
bool listening = false;
169169
bool running = false;
170170
bool first = false;
171+
bool initialized = false;
171172
};
172173
} // namespace fbcpp
173174

0 commit comments

Comments
 (0)