Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- FixedSizeQueue::FixedSizeQueue(const std::string& filename, size_t size)
- : size_(size)
- , head_(0)
- , tail_(0)
- {
- fopen_s(&file_, filename.c_str(), "w+");
- InitializeCriticalSection(&critical_section_);
- }
- void
- FixedSizeQueue::push_values(int* values, size_t count)
- {
- Logger::report("Called push_values");
- EnterCriticalSection(&critical_section_);
- size_t free_items = (tail_ > head_) ? size_ - tail_ + head_ : size_ - head_ + tail_;
- if (count > free_items)
- {
- Logger::report("Buffer is full, can't push new values.");
- exit(1);
- }
- size_t till_end = (tail_ >= head_) ? size_ - tail_ : head_ - tail_;
- if (count < till_end)
- {
- fseek(file_, tail_ * sizeof(int), SEEK_SET);
- int g = fwrite(values, sizeof(int), count, file_);
- assert(g == count);
- tail_ += count;
- }
- else
- {
- fseek(file_, tail_ * sizeof(int), SEEK_SET);
- int h = fwrite(values, sizeof(int), till_end, file_);
- assert(h == till_end);
- fseek(file_, tail_ * sizeof(int), SEEK_SET);
- h = fwrite(values + count, sizeof(int), count - till_end, file_);
- assert(h == count - till_end);
- tail_ = count - till_end;
- }
- fflush(file_);
- LeaveCriticalSection(&critical_section_);
- }
- size_t
- FixedSizeQueue::get_values(int* values)
- {
- Logger::report("Called get_values");
- EnterCriticalSection(&critical_section_);
- const size_t item_count = (tail_ >= head_) ? tail_ - head_ : size_ - head_ + tail_;
- if (tail_ > head_)
- {
- fseek(file_, head_ * sizeof(int), SEEK_SET);
- fread(values, sizeof(int), item_count, file_);
- }
- else
- {
- fseek(file_, (size_ - head_) * sizeof(int), SEEK_SET);
- fread(values, sizeof(int), size_ - head_, file_);
- fseek(file_, 0, SEEK_SET);
- fread(values + size_ - head_, sizeof(int), tail_, file_);
- }
- head_ = tail_ = 0;
- LeaveCriticalSection(&critical_section_);
- return item_count;
- }
- fopen_s( path, "wc") // w - write mode, c - allow immediate commit to disk
- _flushall()
- fclose()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement