多线程使用者未产生与使用升压环形缓冲区的输入相同的输出
multithreading consumer not producing same output as input using boost ringbuffer
在我的主程序中,我将字符串缓冲区复制到 boost 环形缓冲区中,然后尝试在创建的线程中使用该数据并写入文件。在主线程中,我也将相同的数据写入文件,但输入和输出文件都不匹配。
我觉得我正在做一件非常愚蠢的事情。请帮忙。此外,如果有任何改进代码的建议,我们将不胜感激。
#include <iostream>
#include <vector>
#include <boost/circular_buffer.hpp>
#include <numeric>
#include <assert.h>
#include <thread>
#include <mutex>
#include <chrono>
#include <time.h>
#include <cstdint>
#include <fstream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::string;
#define SOME_FIXED_HARDCODED_NUMBER 40980
class MyClass {
public:
std::vector<int8_t> vec;
public:
MyClass(std::vector<int8_t> v){ vec = v; }
};
boost::circular_buffer<MyClass> cb(300);
int waiting = 1;
std::mutex my_mutex;
FILE *out_file;
FILE *in_file;
void foo()
{
while (waiting) {
std::unique_lock<std::mutex> lock(my_mutex);
if (!cb.size() || waiting == 0) {
lock.unlock();
continue;
}
if (!waiting)
break;
MyClass local_buf = cb.front();
cb.pop_front();
fwrite(local_buf.vec.data(), 1, local_buf.vec.size(), out_file);
}
}
int main(int argc, char* argv[])
{
out_file = fopen("output_data.raw", "w");
in_file = fopen("input_data.raw", "w");
std::thread th1(foo);
char *buf = {"abc"};
int counter = 0;
std::vector<int8_t> mem;
mem.insert(mem.end(), buf, buf + strlen(buf));
while (counter < SOME_FIXED_HARDCODED_NUMBER)
{
{
std::unique_lock<std::mutex> lock(my_mutex);
/* if the circular buffer is full then wait for consumer to pull the data */
while (cb.full()) {
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::unique_lock<std::mutex> lock(my_mutex);
}
cb.push_front(MyClass(mem));
fwrite(mem.data(), 1, mem.size(), in_file);
}
counter++;
}
waiting = 0;
th1.join();
fclose(out_file);
fclose(in_file);
return 0;
}
while (cb.full()) {
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
>>> std::unique_lock<std::mutex> lock(my_mutex);
}
标记的unique_lock
不执行任何操作,因为它将立即超出范围并解锁互斥锁。因此,一旦你离开循环,互斥锁就不会被锁定,你就有一个竞争条件。相反,您应该使用lock.lock()
重新锁定互斥锁。
还有一些错误。您不是在等待foo
线程实际耗尽缓冲区。一旦主线程设置了等待标志,它就会停止。此外,等待应该是一个原子。
相关文章:
- 套接字读取后,我在缓冲区中看到意外输入
- 清除输入缓冲区后未提取字符串流
- 快速读取标准输入缓冲区,无需检查
- C++ 为什么还剩下输入缓冲区?
- C++ - 有什么方法可以将输入插入缓冲区/停止 cin.忽略需要输入?
- 如果输入缓冲区不为空,请使用getchar.()检测Ctrl+d
- 如果我在 C++ 中为 int 提供双精度,输入缓冲区中存储了什么?
- 有没有办法将两个输入图像堆叠到卤化物发生器中的单个 4 维缓冲区中?
- 用于了解输入和输出流缓冲区实际工作方式的程序
- 如何重复使用原始输入缓冲区内存?
- 从输入缓冲区读取
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 多线程使用者未产生与使用升压环形缓冲区的输入相同的输出
- 从超强的AndroidAudioIO输入读取缓冲区
- 安全操作以清除C++中的空输入缓冲区
- 如何检查输入缓冲区是否为空
- 我可以做一个循环,直到“std::cin”在输入缓冲区中看到“”字符
- 从gstreamer缓冲区创建输入张量
- 从缓冲区输入的位
- Directx10,实例化渲染,顶点缓冲区输入