【发布时间】:2019-11-16 17:44:32
【问题描述】:
我想在一个线程中读取二进制文件并在另一个线程中写入它。它适用于小文件(如 txt 文件)但不适用于大文件(如 jpg 文件)。我尝试在向量中存储缓冲区,但它像队列一样工作。
#include <iostream>
#include <thread>
#include <queue>
#include <fstream>
#include <unistd.h>
#include <mutex>
#include <string>
using namespace std;
std::mutex mtx;
vector<char *> q;
const int MAX_QUEUE_LENGTH = 100;
int string_size(char * str)
{
int Size = 0;
while (str[Size] != '\0') Size++;
return Size;
}
void readFile()
{
ifstream file;
file.open("in.jpg", ios::binary);
file.seekg(0, ios::end);
int length = file.tellg();
cout << length;
file.seekg(0, ios::beg);
while (true) {
mtx.lock();
if (q.size() > MAX_QUEUE_LENGTH) {
mtx.unlock();
sleep(10);
continue;
}
if (length - file.tellg() <= 1024) {
int tmp = length - file.tellg();
char *c = new char[tmp];
file.read(c,tmp);
q.push_back(c);
mtx.unlock();
break;
} else {
char *c = new char[1024];
file.read(c,1024);
q.push_back(c);
mtx.unlock();
}
}
file.close();
}
void writeFile() {
ofstream o;
o.open("out.jpg", ios::binary);
while (true) {
mtx.lock();
if(q.empty()) {
mtx.unlock();
sleep(5);
mtx.lock();
}
if(q.empty()) break;
o.write(q.front(), string_size(q.front()));
q.erase(q.begin());
mtx.unlock();
}
o.close();
}
int main() {
thread th_in(readFile);
thread th_out(writeFile);
th_in.join();
th_out.join();
}
【问题讨论】:
-
与其手动使用
std::mutex::lock()和std::mutex::unlock(),不如考虑使用std::lock_guard。 -
解释您的问题“它不起作用”。碰撞?输出错误?
-
输出错误!!! out.jpg 应该是图片,但它是奇怪的符号字符串!
标签: c++ multithreading file binary