You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by sw...@apache.org on 2026/09/14 02:44:44 UTC
(logging-log4cxx) branch master updated: Prevent a missed wake-up of the background thread (#761)
This is an automated email from the ASF dual-hosted git repository.
swebb2066 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/logging-log4cxx.git
The following commit(s) were added to refs/heads/master by this push:
new 3efffa89 Prevent a missed wake-up of the background thread (#761)
3efffa89 is described below
commit 3efffa89425374a05153b4863be0abb1e2be428b
Author: Stephen Webb <st...@ieee.org>
AuthorDate: Mon Sep 14 12:44:39 2026 +1000
Prevent a missed wake-up of the background thread (#761)
* Prevent occasional faults in the ThreadUtility test (credit to Gemini)
* Improve support for periodic task testing
---
.github/workflows/log4cxx-macos.yml | 7 ++
src/main/cpp/threadutility.cpp | 131 +++++++++++++----------
src/main/include/CMakeLists.txt | 2 +-
src/main/include/log4cxx/helpers/threadutility.h | 5 +
src/test/cpp/helpers/threadutilitytestcase.cpp | 21 +++-
5 files changed, 103 insertions(+), 63 deletions(-)
diff --git a/.github/workflows/log4cxx-macos.yml b/.github/workflows/log4cxx-macos.yml
index b46cd04c..56a62570 100644
--- a/.github/workflows/log4cxx-macos.yml
+++ b/.github/workflows/log4cxx-macos.yml
@@ -102,3 +102,10 @@ jobs:
cd main
cd build
ctest -C Debug --output-on-failure
+ if [ -n "${{ matrix.test_until_fail }}" ]; then
+ runNo=1
+ while ctest -C Debug --output-on-failure -R ${{ matrix.test_until_fail }} ; do
+ runNo=`expr $runNo + 1`
+ done
+ echo "$runNo failed"
+ fi
diff --git a/src/main/cpp/threadutility.cpp b/src/main/cpp/threadutility.cpp
index 230cad8d..47d2db20 100644
--- a/src/main/cpp/threadutility.cpp
+++ b/src/main/cpp/threadutility.cpp
@@ -80,6 +80,7 @@ struct ThreadUtility::priv_data
std::thread thread;
std::condition_variable interrupt;
std::mutex interrupt_mutex;
+ bool wakeup{ false };
std::atomic<bool> terminated{ false };
int retryCount{ 2 };
Period maxDelay{ 0 };
@@ -88,17 +89,28 @@ struct ThreadUtility::priv_data
void doPeriodicTasks();
+ bool findRunnableTask(NamedPeriodicFunction *foundTask);
+
+ void scheduleNextRun(const LogString& name, const Period& delay, bool success);
+
void setTerminated()
{
std::lock_guard<std::recursive_mutex> lock(job_mutex);
terminated.store(true);
}
+
+ void wakeThread()
+ {
+ std::unique_lock<std::mutex> lock(this->interrupt_mutex);
+ this->wakeup = true;
+ this->interrupt.notify_all();
+ }
void stopThread()
{
LOGLOG_DEBUG(log, "stopThread");
setTerminated();
- interrupt.notify_all();
+ wakeThread();
if (thread.joinable())
thread.join();
}
@@ -295,7 +307,15 @@ void ThreadUtility::addPeriodicTask(const LogString& name, std::function<void()>
});
}
else
- m_priv->interrupt.notify_one();
+ m_priv->wakeThread();
+}
+
+/**
+ * Is this currently running a background thread?
+ */
+bool ThreadUtility::isProcessingThreadActive() const
+{
+ return m_priv->threadIsActive.load();
}
/**
@@ -339,7 +359,7 @@ void ThreadUtility::removePeriodicTask(const LogString& name)
{
LOGLOG_DEBUG(m_priv->log, LOG4CXX_STR("removePeriodicTask: ") << name);
pItem->removed = true;
- m_priv->interrupt.notify_one();
+ m_priv->wakeThread();
}
}
@@ -359,7 +379,7 @@ void ThreadUtility::removePeriodicTasksMatching(const LogString& namePrefix)
break;
pItem->removed = true;
}
- m_priv->interrupt.notify_one();
+ m_priv->wakeThread();
}
// Run ready tasks
@@ -367,76 +387,33 @@ void ThreadUtility::priv_data::doPeriodicTasks()
{
while (!this->terminated.load())
{
- auto currentTime = std::chrono::system_clock::now();
- TimePoint nextOperationTime = currentTime + this->maxDelay;
+ TimePoint nextOperationTime = std::chrono::system_clock::now() + this->maxDelay;
// Run each due task with job_mutex released, so a long-running callback
// (e.g. a reconnect blocked on network I/O) does not stall removePeriodicTask()
- while (true)
+ while (!this->terminated.load())
{
- std::function<void()> taskCallback;
- LogString taskName;
- Period taskDelay;
- bool foundTask = false;
-
- // Take a copy of the next due task while holding the lock
- {
- if (this->terminated.load())
- return;
- std::lock_guard<std::recursive_mutex> lock(this->job_mutex);
- auto pItem = std::find_if(this->jobs.begin(), this->jobs.end()
- , [currentTime](const NamedPeriodicFunction& item)
- { return !item.removed && item.nextRun <= currentTime; }
- );
- if (pItem != this->jobs.end())
- {
- taskCallback = pItem->f;
- taskName = pItem->name;
- taskDelay = pItem->delay;
- foundTask = true;
- }
- }
-
- // No more tasks are due, leave the loop
- if (!foundTask)
- {
+ NamedPeriodicFunction task;
+ if (!this->findRunnableTask(&task)) // No tasks due?
break;
- }
- // Execute the callback outside the lock
+ // Execute the callback outside any lock
bool success = false;
try
{
- taskCallback();
+ task.f();
success = true;
}
catch (std::exception& ex)
{
- LogLog::warn(taskName, ex);
+ LogLog::warn(task.name, ex);
}
catch (...)
{
- LogLog::warn(taskName + LOG4CXX_STR(" threw an exception"));
+ LogLog::warn(task.name + LOG4CXX_STR(" threw an exception"));
}
- // Re-find the task (it may have been removed while running) and reschedule it
- {
- std::lock_guard<std::recursive_mutex> lock(this->job_mutex);
- auto pItem = std::find_if(this->jobs.begin(), this->jobs.end()
- , [&taskName](const NamedPeriodicFunction& item)
- { return !item.removed && taskName == item.name; }
- );
-
- if (pItem != this->jobs.end())
- {
- // Always push nextRun out, so a failing task waits before the next retry
- pItem->nextRun = std::chrono::system_clock::now() + taskDelay;
- if (success)
- pItem->errorCount = 0;
- else
- ++pItem->errorCount;
- }
- }
+ this->scheduleNextRun(task.name, task.delay, success);
}
// Update nextOperationTime under the lock
@@ -469,7 +446,47 @@ void ThreadUtility::priv_data::doPeriodicTasks()
// Wait until the next task is due or an add/remove/shutdown wakes us
std::unique_lock<std::mutex> lock(this->interrupt_mutex);
- this->interrupt.wait_until(lock, nextOperationTime);
+ this->interrupt.wait_until(lock, nextOperationTime
+ , [this]{ return this->wakeup; }
+ );
+ this->wakeup = false;
+ }
+}
+
+bool ThreadUtility::priv_data::findRunnableTask(NamedPeriodicFunction *foundTask)
+{
+ std::lock_guard<std::recursive_mutex> lock(this->job_mutex);
+ bool result = false;
+ auto currentTime = std::chrono::system_clock::now();
+ auto pItem = std::find_if(this->jobs.begin(), this->jobs.end()
+ , [currentTime](const NamedPeriodicFunction& item)
+ { return !item.removed && item.nextRun <= currentTime; }
+ );
+ if (pItem != this->jobs.end())
+ {
+ if (foundTask)
+ *foundTask = *pItem;
+ result = true;
+ }
+ return result;
+}
+
+void ThreadUtility::priv_data::scheduleNextRun(const LogString& name, const Period& delay, bool success)
+{
+ std::lock_guard<std::recursive_mutex> lock(this->job_mutex);
+ auto pItem = std::find_if(this->jobs.begin(), this->jobs.end()
+ , [&name](const NamedPeriodicFunction& item)
+ { return !item.removed && name == item.name; }
+ );
+
+ if (pItem != this->jobs.end())
+ {
+ // Always push nextRun out, so a failing task waits before the next retry
+ pItem->nextRun = std::chrono::system_clock::now() + delay;
+ if (success)
+ pItem->errorCount = 0;
+ else
+ ++pItem->errorCount;
}
}
diff --git a/src/main/include/CMakeLists.txt b/src/main/include/CMakeLists.txt
index 2a2a7c2a..22f68834 100644
--- a/src/main/include/CMakeLists.txt
+++ b/src/main/include/CMakeLists.txt
@@ -80,7 +80,7 @@ else()
set(MULTIPROCESS_RFA 0)
endif()
-option(LOG4CXX_EVENTS_AT_EXIT "Prevent static data cleanup to allow event logging during application exit. Note: Appenders should not configure the \"BufferedIO\" option to true." OFF)
+option(LOG4CXX_EVENTS_AT_EXIT "Prevent static data cleanup to allow event logging during application exit" OFF)
if(LOG4CXX_EVENTS_AT_EXIT )
set(EVENTS_AT_EXIT 1)
else()
diff --git a/src/main/include/log4cxx/helpers/threadutility.h b/src/main/include/log4cxx/helpers/threadutility.h
index 583e8ff1..d662e988 100644
--- a/src/main/include/log4cxx/helpers/threadutility.h
+++ b/src/main/include/log4cxx/helpers/threadutility.h
@@ -164,6 +164,11 @@ class LOG4CXX_EXPORT ThreadUtility
*/
bool hasPeriodicTask(const LogString& taskName);
+ /**
+ * Is the processing thread running?
+ */
+ bool isProcessingThreadActive() const;
+
/**
* Remove all periodic tasks and stop the processing thread
*/
diff --git a/src/test/cpp/helpers/threadutilitytestcase.cpp b/src/test/cpp/helpers/threadutilitytestcase.cpp
index aa5203c7..0d1174d4 100644
--- a/src/test/cpp/helpers/threadutilitytestcase.cpp
+++ b/src/test/cpp/helpers/threadutilitytestcase.cpp
@@ -152,8 +152,13 @@ public:
}
thrUtil->removePeriodicTask(secondTask);
LOGUNIT_ASSERT(0 < secondRuns.load());
- // wait 30 ms for periodic task thread to exit
- std::this_thread::sleep_for(std::chrono::milliseconds(30));
+
+ // Wait until periodic tasks are destroyed
+ for (int i = 0; i < 100 && thrUtil->isProcessingThreadActive(); ++i)
+ {
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ LOGUNIT_ASSERT(!thrUtil->isProcessingThreadActive());
}
void testNoDeadlockDuringTaskExecution()
@@ -165,10 +170,14 @@ public:
thrUtil->removeAllPeriodicTasks();
// A callback that blocks, as a reconnect attempt would when the log server is offline
- thrUtil->addPeriodicTask(slowTask, [&taskRunning, &releaseTask]() {
+ auto logger= LogLog::getLogger(LOG4CXX_STR("testTask"));
+ thrUtil->addPeriodicTask(slowTask, [&taskRunning, &releaseTask, &logger]() {
+ LOGLOG_DEBUG(logger, LOG4CXX_STR("started"));
taskRunning = true;
for (int i = 0; i < 500 && !releaseTask.load(); ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ LOGLOG_DEBUG(logger, LOG4CXX_STR("stopped"));
+ taskRunning = false;
}, std::chrono::milliseconds(1));
// Wait for the callback to start executing
@@ -184,8 +193,10 @@ public:
releaseTask = true;
LOGUNIT_ASSERT(std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count() < 1000);
- // wait for the periodic task thread to settle
- std::this_thread::sleep_for(std::chrono::milliseconds(50));
+ // wait for the lambda task thread to complete
+ for (int i = 0; i < 100 && taskRunning.load(); ++i)
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ LOGUNIT_ASSERT(!taskRunning.load());
}
void testThreadNameLogging()