From ff99088eb0dd798d2e599a3bcfc3bc024a62034d Mon Sep 17 00:00:00 2001 From: Pranav Subbaraman Date: Wed, 5 Mar 2025 18:18:13 -0800 Subject: [PATCH 1/2] Lamport Clock implementation. This contains the full class and full implementation --- LamportClock.c | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 LamportClock.c diff --git a/LamportClock.c b/LamportClock.c new file mode 100644 index 0000000..fc0d80a --- /dev/null +++ b/LamportClock.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include + +class LamportClock { +private: + unsigned long timestamp; + std::mutex mtx; + +public: + LamportClock() : timestamp(0) {} + + unsigned long tick() { + std::lock_guard lock(mtx); + timestamp++; + return timestamp; + } + + unsigned long update(unsigned long received) { + std::lock_guard lock(mtx); + timestamp = std::max(timestamp, received) + 1; + return timestamp; + } + + + unsigned long get_time() { + std::lock_guard lock(mtx); + return timestamp; + } +}; + +// Logger: Logs messages with Lamport Logical Clock timestamps +class Logger { +private: + std::ofstream log_file; + LamportClock clock; + std::mutex log_mtx; + +public: + Logger(const std::string &filename) { + log_file.open(filename, std::ios::out | std::ios::app); + if (!log_file.is_open()) { + throw std::runtime_error("Cannot open log file: " + filename); + } + } + + ~Logger() { + if (log_file.is_open()) { + log_file.close(); + } + } + + // Logs an internal event. The logical clock is incremented. + void log(const std::string &node_id, const std::string &source_filename, int line_number, const std::string &message) { + unsigned long ts = clock.tick(); + std::lock_guard lock(log_mtx); + log_file << ts << " " << node_id << " " << source_filename << " " << line_number << " " << message << std::endl; + } + + // Logs an external event that carries a Lamport timestamp. + void log_received(const std::string &node_id, const std::string &source_filename, int line_number, const std::string &message, unsigned long received_timestamp) { + unsigned long ts = clock.update(received_timestamp); + std::lock_guard lock(log_mtx); + log_file << ts << " " << node_id << " " << source_filename << " " << line_number << " " << message << std::endl; + } +}; \ No newline at end of file From fdbc49b99b7cad8f4f6496fc3805121027956809 Mon Sep 17 00:00:00 2001 From: Daniel Yang Date: Wed, 5 Mar 2025 19:30:04 -0800 Subject: [PATCH 2/2] force c++ 17 --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a08593..984338e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,7 @@ cmake_minimum_required(VERSION 3.15) project(distributed-tracing VERSION 1.0 LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(BUILD_DIRECTORY build)