Skip to content

Commit

Permalink
[wpiutil] DataLog: Ensure file is written on shutdown (#6087)
Browse files Browse the repository at this point in the history
Previously the thread could end without the file being written.
  • Loading branch information
PeterJohnson authored Dec 23, 2023
1 parent c29e8c6 commit 21d1972
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
10 changes: 5 additions & 5 deletions wpiutil/src/main/native/cpp/DataLog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ DataLog::DataLog(wpi::Logger& msglog,
DataLog::~DataLog() {
{
std::scoped_lock lock{m_mutex};
m_state = kShutdown;
m_shutdown = true;
m_doFlush = true;
}
m_cond.notify_all();
Expand Down Expand Up @@ -419,7 +419,7 @@ void DataLog::WriterThreadMain(std::string_view dir) {
uintmax_t written = 0;

std::unique_lock lock{m_mutex};
while (m_state != kShutdown) {
do {
bool doFlush = false;
auto timeoutTime = std::chrono::steady_clock::now() + periodTime;
if (m_cond.wait_until(lock, timeoutTime) == std::cv_status::timeout) {
Expand Down Expand Up @@ -557,7 +557,7 @@ void DataLog::WriterThreadMain(std::string_view dir) {
}
toWrite.resize(0);
}
}
} while (!m_shutdown);
}

void DataLog::WriterThreadMain(
Expand All @@ -580,7 +580,7 @@ void DataLog::WriterThreadMain(
std::vector<Buffer> toWrite;

std::unique_lock lock{m_mutex};
while (m_state != kShutdown) {
do {
bool doFlush = false;
auto timeoutTime = std::chrono::steady_clock::now() + periodTime;
if (m_cond.wait_until(lock, timeoutTime) == std::cv_status::timeout) {
Expand Down Expand Up @@ -614,7 +614,7 @@ void DataLog::WriterThreadMain(
}
toWrite.resize(0);
}
}
} while (!m_shutdown);

write({}); // indicate EOF
}
Expand Down
2 changes: 1 addition & 1 deletion wpiutil/src/main/native/include/wpi/DataLog.h
Original file line number Diff line number Diff line change
Expand Up @@ -486,12 +486,12 @@ class DataLog final {
mutable wpi::mutex m_mutex;
wpi::condition_variable m_cond;
bool m_doFlush{false};
bool m_shutdown{false};
enum State {
kStart,
kActive,
kPaused,
kStopped,
kShutdown,
} m_state = kActive;
double m_period;
std::string m_extraHeader;
Expand Down
18 changes: 18 additions & 0 deletions wpiutil/src/test/native/cpp/DataLogTest.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.

#include <gtest/gtest.h>

#include "wpi/DataLog.h"

TEST(DataLogTest, SimpleInt) {
std::vector<uint8_t> data;
{
wpi::log::DataLog log{
[&](auto out) { data.insert(data.end(), out.begin(), out.end()); }};
int entry = log.Start("test", "int64");
log.AppendInteger(entry, 1, 0);
}
ASSERT_EQ(data.size(), 66u);
}

0 comments on commit 21d1972

Please sign in to comment.