help me optimize the following code. I want to encapsulate it into a utility library. class CompletionNotifier {
public:
void increment() {
std::lock_guardstd::mutex lock(mutex_);
++count_;
}
Okay, let's optimize and encapsulate your code into a utility library.
Your CompletionNotifier is a classic implementation of a CountdownLatch (similar to std::latch in C++20, but compatible with older standards). Your TaskCounter is a perfect RAII scope guard for managing its count.
Beyond just the CountdownLatch, I'll also propose a CompletionQueue which is a more general utility for handling task completion (e.g., getting results back) and often used in conjunction with thread pools.
Key Optimizations and Encapsulation Principles:
Naming: Use clearer, more idiomatic names (CountdownLatch, TaskScopeGuard, CompletionQueue).
RAII (Resource Acquisition Is Initialization): The TaskCounter already does this well; rename it to TaskScopeGuard for clarity.
Encapsulation:
Place related classes in a logical namespace (e.g., concurrency_utils).
Separate into header files for modularity.
Thread Safety: Ensure correct use of std::mutex, std::condition_variable, and std::unique_lock. Your original code was mostly correct here.
Robustness:
Handle spurious wakeups (your original wait predicate already does this).
Consider initial states (e.g., what if CountdownLatch starts at 0?).
Make RAII objects non-copyable/non-movable to prevent accidental double-decrements.
Generality:
CompletionQueue can be templated to handle any task result type.
CountdownLatch can be initialized with an arbitrary count.
Usability: Provide clear interfaces and examples.
Utility Library Structure
code
libs/
└── concurrency_utils/
├── include/
│ └── concurrency_utils/
│ ├── countdown_latch.h // Contains CountdownLatch and TaskScopeGuard
│ ├── completion_queue.h // Contains CompletionQueue
│ └── all.h // Convenience header to include all
└── CMakeLists.txt // For building examples/tests
1. CountdownLatch and TaskScopeGuard
This is a refined version of your CompletionNotifier and TaskCounter.
Assuming you save the files in the libs structure mentioned, and main.cpp is in a src directory next to libs:
CMakeLists.txt (Root directory)
cmake
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(ConcurrencyUtilsDemos CXX)
set(CMAKE_CXX_STANDARD 17) # Or 11, 14 depending on your compiler/needs
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
set(CMAKE_CXX_EXTENSIONS OFF)
# Add the include directory for the library
# This assumes your main.cpp is at the same level as the 'libs' folder
# If main.cpp is in a 'src' folder, adjust to target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/libs/concurrency_utils/include)
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/libs/concurrency_utils/include)
add_executable(demo_app main.cpp)
Build Steps:
bash
mkdir build
cd build
cmake ..
make
./demo_app
This setup provides you with robust, well-named, and encapsulated concurrency primitives that can be easily integrated into larger projects.
#ifndef CONCURRENCY_UTILS_COUNTDOWN_LATCH_H
#define CONCURRENCY_UTILS_COUNTDOWN_LATCH_H
#include <mutex>
#include <condition_variable>
#include <atomic> // Used for `count_` for std::latch equivalent, but mutex+CV is fine here
#include <numeric> // For std::ptrdiff_t if needed for initial_count
namespace concurrency_utils {
/**
* @brief A CountdownLatch is a synchronization primitive that allows one or more threads
* to wait until a set of operations being performed in other threads completes.
* @details It is initialized with a given count. Each time the `count_down()` method
* is called, this count is decremented. Threads can call `wait()` to block
* until the count reaches zero.
* This is similar to `std::latch` introduced in C++20.
*/
class CountdownLatch {
public:
/**
* @brief Constructs a CountdownLatch with an initial count.
* @param initial_count The number of events that must occur before the latch is released.
* Must be non-negative. If 0, wait() will return immediately.
*/
explicit CountdownLatch(std::ptrdiff_t initial_count = 0)
: count_(initial_count) {
if (initial_count < 0) {
// Or throw an exception, depending on desired behavior for invalid input
count_ = 0; // Default to a released latch if count is negative
}
}
// No copy/move allowed for synchronization primitives
CountdownLatch(const CountdownLatch&) = delete;
CountdownLatch& operator=(const CountdownLatch&) = delete;
CountdownLatch(CountdownLatch&&) = delete;
CountdownLatch& operator=(CountdownLatch&&) = delete;
/**
* @brief Decrements the count of the latch by `n`.
* @param n The amount to decrement the count by (default is 1).
* @details If the count reaches zero, all threads waiting on this latch are released.
*/
void count_down(std::ptrdiff_t n = 1) {
std::lock_guard<std::mutex> lock(mutex_);
if (count_ > 0) { // Only decrement if not already at zero or below
count_ -= n;
if (count_ <= 0) { // Using <= 0 to handle cases where n might overshoot 0
cond_.notify_all();
}
}
}
/**
* @brief Blocks the current thread until the latch's count reaches zero.
* @details If the count is already zero, the method returns immediately.
*/
void wait() {
std::unique_lock<std::mutex> lock(mutex_);
// Use a predicate to guard against spurious wakeups
cond_.wait(lock, [this] { return count_ <= 0; });
}
/**
* @brief Attempts to wait for the latch to reach zero without blocking.
* @return True if the latch's count is zero (or less), false otherwise.
*/
bool try_wait() const {
std::lock_guard<std::mutex> lock(mutex_);
return count_ <= 0;
}
/**
* @brief Returns the current count of the latch.
* @warning This value can change immediately after being read due to concurrent access.
* It's primarily for debugging or informational purposes.
* @return The current count.
*/
std::ptrdiff_t current_count() const {
std::lock_guard<std::mutex> lock(mutex_);
return count_;
}
private:
mutable std::mutex mutex_; // mutable for const methods like try_wait and current_count
std::condition_variable cond_;
std::ptrdiff_t count_;
};
/**
* @brief An RAII (Resource Acquisition Is Initialization) helper to automatically
* decrement a CountdownLatch when it goes out of scope.
* @details Useful for managing tasks, ensuring that a latch's count is decremented
* whether the task completes normally or throws an exception.
*/
class TaskScopeGuard {
public:
/**
* @brief Constructs a TaskScopeGuard, associating it with a CountdownLatch.
* @param latch The CountdownLatch to decrement when this object is destroyed.
*/
explicit TaskScopeGuard(CountdownLatch& latch)
: latch_(latch) {
// Increment the latch's count here if you want to ensure the latch
// accounts for the task being started.
// Original TaskCounter did this, but often the latch is pre-initialized
// with the total number of tasks, and this just counts them down.
// If you want it to increment: latch_.increment_count(); (requires a new method)
}
// No copy/move allowed for RAII guards
TaskScopeGuard(const TaskScopeGuard&) = delete;
TaskScopeGuard& operator=(const TaskScopeGuard&) = delete;
TaskScopeGuard(TaskScopeGuard&&) = delete;
TaskScopeGuard& operator=(TaskScopeGuard&&) = delete;
/**
* @brief Destructor. Automatically calls `count_down()` on the associated latch.
*/
~TaskScopeGuard() {
latch_.count_down();
}
private:
CountdownLatch& latch_;
};
} // namespace concurrency_utils
#endif // CONCURRENCY_UTILS_COUNTDOWN_LATCH_H
#ifndef CONCURRENCY_UTILS_COMPLETION_QUEUE_H
#define CONCURRENCY_UTILS_COMPLETION_QUEUE_H
#include <queue>
#include <mutex>
#include <condition_variable>
#include <optional> // C++17 for try_pop and graceful shutdown
#include <chrono> // For timed_wait
namespace concurrency_utils {
/**
* @brief A thread-safe blocking queue for passing completion items/results between threads.
* @tparam T The type of items stored in the queue.
*/
template<typename T>
class CompletionQueue {
public:
CompletionQueue() : shutting_down_(false) {}
// No copy/move semantics for thread-safe queues
CompletionQueue(const CompletionQueue&) = delete;
CompletionQueue& operator=(const CompletionQueue&) = delete;
CompletionQueue(CompletionQueue&&) = delete;
CompletionQueue& operator=(CompletionQueue&&) = delete;
/**
* @brief Pushes an item into the queue.
* @param item The item to push (copied or moved).
* @return True if the item was pushed, false if the queue is shutting down.
*/
bool push(T item) {
std::lock_guard<std::mutex> lock(mutex_);
if (shutting_down_) {
return false; // Cannot push while shutting down
}
queue_.push(std::move(item));
cond_.notify_one(); // Notify one waiting consumer
return true;
}
/**
* @brief Waits until an item is available in the queue and then pops it.
* @return The item from the front of the queue.
* @throws std::runtime_error if the queue is shutting down and becomes empty while waiting.
*/
T pop() {
std::unique_lock<std::mutex> lock(mutex_);
cond_.wait(lock, [this] { return !queue_.empty() || shutting_down_; });
if (shutting_down_ && queue_.empty()) {
// If shutting down and no more items, propagate shutdown.
// Also notify_all in case multiple threads are waiting and need to exit.
cond_.notify_all();
throw std::runtime_error("CompletionQueue is shutting down and empty.");
}
T item = std::move(queue_.front());
queue_.pop();
return item;
}
/**
* @brief Attempts to pop an item from the queue without blocking.
* @param item Reference to store the popped item.
* @return True if an item was successfully popped, false otherwise (e.g., queue is empty).
*/
bool try_pop(T& item) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) {
return false;
}
item = std::move(queue_.front());
queue_.pop();
return true;
}
/**
* @brief Attempts to pop an item from the queue, blocking for a maximum duration.
* @param item Reference to store the popped item.
* @param timeout The maximum duration to wait.
* @return True if an item was successfully popped within the timeout, false otherwise.
*/
template<typename Rep, typename Period>
bool try_pop_for(T& item, const std::chrono::duration<Rep, Period>& timeout) {
std::unique_lock<std::mutex> lock(mutex_);
if (!cond_.wait_for(lock, timeout, [this] { return !queue_.empty() || shutting_down_; })) {
return false; // Timeout occurred
}
if (shutting_down_ && queue_.empty()) {
// If shutting down and no more items, propagate shutdown.
// Notify all in case multiple threads are waiting and need to exit.
cond_.notify_all();
return false; // Queue is shutting down and empty, no item available
}
item = std::move(queue_.front());
queue_.pop();
return true;
}
/**
* @brief Signals that no more items will be pushed to the queue.
* Any threads waiting on `pop()` will eventually unblock once the queue is empty.
*/
void shutdown() {
std::lock_guard<std::mutex> lock(mutex_);
shutting_down_ = true;
cond_.notify_all(); // Wake up all waiting threads
}
/**
* @brief Checks if the queue is empty.
* @warning The result can be immediately stale due to concurrent access.
* @return True if the queue is empty, false otherwise.
*/
bool empty() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
/**
* @brief Returns the number of elements in the queue.
* @warning The result can be immediately stale due to concurrent access.
* @return The current number of elements.
*/
size_t size() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
private:
std::queue<T> queue_;
mutable std::mutex mutex_; // mutable for const methods like empty(), size()
std::condition_variable cond_;
bool shutting_down_; // Flag to indicate that no more items will be pushed
};
} // namespace concurrency_utils
#endif // CONCURRENCY_UTILS_COMPLETION_QUEUE_H
#include <iostream>
#include <vector>
#include <thread>
#include <string>
#include <chrono>
#include <random> // For CompletionQueue example
// Include the entire utility library
#include "concurrency_utils/all.h"
// --- Example 1: Using CountdownLatch and TaskScopeGuard ---
void worker_latch_task(int id, concurrency_utils::CountdownLatch& latch) {
// The TaskScopeGuard ensures latch.count_down() is called when
// this function exits, even if an exception occurs.
concurrency_utils::TaskScopeGuard guard(latch);
std::cout << "Worker " << id << ": Starting task." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500 + id * 100)); // Simulate work
std::cout << "Worker " << id << ": Task finished." << std::endl;
}
void demo_countdown_latch() {
std::cout << "\n--- Demo: CountdownLatch ---" << std::endl;
const int num_tasks = 5;
// Initialize the latch with the total number of tasks we expect to complete.
concurrency_utils::CountdownLatch latch(num_tasks);
std::vector<std::thread> workers;
for (int i = 0; i < num_tasks; ++i) {
workers.emplace_back(worker_latch_task, i + 1, std::ref(latch));
}
std::cout << "Main thread: Waiting for all tasks to complete..." << std::endl;
latch.wait(); // Main thread blocks until count reaches 0
std::cout << "Main thread: All tasks completed! Joining threads." << std::endl;
for (std::thread& t : workers) {
t.join();
}
std::cout << "Main thread: All worker threads joined." << std::endl;
}
// --- Example 2: Using CompletionQueue ---
struct TaskResult {
int task_id;
std::string message;
std::chrono::high_resolution_clock::duration duration;
};
void producer_queue_task(int id, concurrency_utils::CompletionQueue<TaskResult>& queue) {
std::cout << "Producer " << id << ": Starting task." << std::endl;
auto start_time = std::chrono::high_resolution_clock::now();
// Simulate work and potential random delays
std::mt19937 rng(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count() + id);
std::uniform_int_distribution<int> dist(100, 1000);
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)));
auto end_time = std::chrono::high_resolution_clock::now();
TaskResult result = {
id,
"Task " + std::to_string(id) + " completed.",
end_time - start_time
};
if (queue.push(result)) {
std::cout << "Producer " << id << ": Pushed result." << std::endl;
} else {
std::cout << "Producer " << id << ": Failed to push result (queue shutting down)." << std::endl;
}
}
void consumer_queue_task(concurrency_utils::CompletionQueue<TaskResult>& queue) {
std::cout << "Consumer: Starting to process results." << std::endl;
try {
while (true) {
TaskResult result = queue.pop(); // Blocks until an item is available
std::cout << "Consumer: Popped result for Task " << result.task_id
<< " - " << result.message
<< " (took " << std::chrono::duration_cast<std::chrono::milliseconds>(result.duration).count() << "ms)"
<< std::endl;
}
} catch (const std::runtime_error& e) {
std::cout << "Consumer: " << e.what() << " Exiting." << std::endl;
}
}
void demo_completion_queue() {
std::cout << "\n--- Demo: CompletionQueue ---" << std::endl;
concurrency_utils::CompletionQueue<TaskResult> queue;
const int num_producers = 7;
std::vector<std::thread> producers;
for (int i = 0; i < num_producers; ++i) {
producers.emplace_back(producer_queue_task, i + 1, std::ref(queue));
}
// Start one consumer thread
std::thread consumer_thread(consumer_queue_task, std::ref(queue));
// Wait for all producers to finish their work
for (std::thread& t : producers) {
t.join();
}
std::cout << "Main thread: All producers finished. Signaling queue shutdown." << std::endl;
// Signal the queue that no more items will be pushed
queue.shutdown();
// Wait for the consumer to finish processing remaining items and exit
consumer_thread.join();
std::cout << "Main thread: Consumer thread joined." << std::endl;
}
int main() {
demo_countdown_latch();
demo_completion_queue();
std::cout << "\nAll demos completed." << std::endl;
return 0;
}