Skip to content

Instantly share code, notes, and snippets.

@ayushgun
ayushgun / buffer.hpp
Last active November 17, 2023 19:39
A simple, generic buffer that accumulates items in a queue and processes them when a specified capacity is reached.
#pragma once
#include <cstddef>
#include <functional>
#include <queue>
// A buffer class that accumulates items in a queue and processes them when a
// specified capacity is reached.
template <typename T, std::size_t Capacity>
class Buffer {
@ayushgun
ayushgun / mutex_example.cpp
Last active September 26, 2023 03:01
Example of the usage of std::mutex in writing thread-safe code. The mutex locks prior to modifying the vector member of the log class. This makes any other threads also modifying the vector via the addCode method wait until the mutex unlocks. Thus, only one thread can call addCode at a time. Would be better to use a std::lock_guard.
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
// Thread-safe implementation of a log
class Log {
private:
std::vector<int> codeLog;
@ayushgun
ayushgun / future_example.cpp
Last active August 20, 2023 16:20
Example of usage of std::future and std::async for multithreaded computation.
#include <future>
#include <iostream>
#include <numeric>
#include <vector>
// Returns the sum of all integers between [1, n]
int sum(const unsigned int n) {
std::vector<int> numbers(n);
std::iota(numbers.begin(), numbers.end(), 1);
return std::accumulate(numbers.begin(), numbers.end(), 0);
@ayushgun
ayushgun / barrier_example.cpp
Last active August 20, 2023 15:11
Example of multithreaded loop synchronization using std::barrier.
#include <barrier>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
struct Person {
std::string name;
int age;