Új hozzászólás Aktív témák
-
cog777
őstag
Tobb megoldast kaptam, itt lehet elolvasni.
Lenyeg: van lehetoseg trukkozni, de az tenyleg trukkozes, inkabb template specializaciot valasztanek.Ez a megoldas tetszett jobban:
#include <fmt/format.h>
#include <array>
#include <cstddef>
#include <mutex>
enum class thread_safety_mode {
safe,
unsafe,
};
template <typename T, std::size_t Size, thread_safety_mode Mode>
class circular_buffer;
template <typename T, std::size_t Size>
class circular_buffer<T, Size, thread_safety_mode::unsafe> {
public:
// Push an item to the tail
bool push(const T& item) {
if (is_full()) return false;
buffer_[head_] = item;
head_ = (head_ + 1) % buffer_.size();
return true;
}
// Pop an item from the head
bool pop(T& item) {
if (is_empty()) return false;
item = buffer_[tail_];
tail_ = (tail_ + 1) % buffer_.size();
return true;
}
// Check if the buffer is full
bool is_full() const { return (head_ + 1) % buffer_.size() == tail_; }
// Check if the buffer is empty
bool is_empty() const { return head_ == tail_; }
private:
std::array<T, Size> buffer_;
std::size_t head_{0};
std::size_t tail_{0};
};
template <typename T, std::size_t Size>
class circular_buffer<T, Size, thread_safety_mode::safe> {
public:
bool push(const T& item) {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for push()");
return unsafe_buffer.push(item);
}
// Pop an item from the head
bool pop(T& item) {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for pop()");
return unsafe_buffer.pop(item);
}
// Check if the buffer is full
bool is_full() const {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for is_full()");
return unsafe_buffer.is_full();
}
// Check if the buffer is empty
bool is_empty() const {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for is_empty()");
return unsafe_buffer.is_empty();
}
private:
circular_buffer<T, Size, thread_safety_mode::unsafe> unsafe_buffer{};
mutable std::mutex m{};
};
auto main() -> int {
//
circular_buffer<int, 42, thread_safety_mode::safe> cb{};
cb.push(43);
cb.push(44);
cb.push(45);
int val;
cb.pop(val);
fmt::println("val: {}", val);
cb.pop(val);
fmt::println("val: {}", val);
cb.pop(val);
fmt::println("val: {}", val);
}
Új hozzászólás Aktív témák
● ha kódot szúrsz be, használd a PROGRAMKÓD formázási funkciót!
- Alkatrészt cserélnél vagy bővítenél? Nálunk van, ami kell! Enterprise alkatrészek ITT
- Xbox Game Pass Ultimate kedvező áron, egyenesen a Microsoft-tól! - AUTOMATA BOLT
- Bomba ár HP Pro X360 11 G1 - Intel N4200 I 4GB I 128GB SSD I 11,6" HD Touch I Cam I W10 I Gari
- AKCIÓ! Asus ROG Flow Z13 + ROG XG RTX 3070 - i9 12900H 16GB DDR5 RAM 1TB SSD + RTX 3070 8GB WIN
- Telefon felvásárlás!! Samsung Galaxy S24/Samsung Galaxy S24+/Samsung Galaxy S24 Ultra
Állásajánlatok
Cég: Promenade Publishing House Kft.
Város: Budapest
Cég: PCMENTOR SZERVIZ KFT.
Város: Budapest