我有一个大文件,我必须通过块阅读它。每次当我读块时,我都要做一些耗时的操作,所以我认为多线程读取可能会有所帮助,每个线程都会逐个读取一块并执行操作。这是我在C++编写代码11如何多线程读取C++ 11中的文件?
#include<iostream>
#include<fstream>
#include <condition_variable>
#include <mutex>
#include <thread>
using namespace std;
const int CHAR_PER_FILE = 1e8;
const int NUM_THREAD = 2;
int order = -1;
bool is_reading = false;
mutex mtx;
condition_variable file_not_reading;
void partition(ifstream& is)
{
while (is.peek() != EOF)
{
unique_lock<mutex> lock(mtx);
while (is_reading)
file_not_reading.wait(lock);
is_reading = true;
char *c = new char[CHAR_PER_FILE];
is.read(c, CHAR_PER_FILE);
order++;
is_reading = false;
file_not_reading.notify_all();
lock.unlock();
char oc[3];
sprintf(oc, "%d", order);
this_thread::sleep_for(chrono::milliseconds(2000));//some operations that take long time
ofstream os(oc, ios::binary);
os.write(c, CHAR_PER_FILE);
delete[] c;
os.close();
}
}
int main()
{
ifstream is("bigfile.txt",ios::binary);
thread threads[NUM_THREAD];
for (int i = 0; i < NUM_THREAD; i++)
threads[i] = thread(partition, ref(is));
for (int i = 0; i < NUM_THREAD; i++)
threads[i].join();
is.close();
system("pause");
return 0;
}
但我的代码没有工作,它不仅创造,而不是`bigfilesize/CHAR_PER_FILE 4个文件,和线程似乎卡住了,我怎样才能使它发挥作用?
是否有任何c + + 11多线程读取文件的实现或例子?
谢谢。
'sprintf(oc,“%d”,order);'不受保护意味着'order'可能已经增加,因为解锁和名字很可能不是唯一的。而且你没有对'is.read'进行错误检查,所以你可能会写垃圾。 – molbdnilo 2015-03-13 09:22:28
这里有几个线程安全问题。共享的全局变量需要是“volatile”的。 'ifstream'不是线程安全的,但它被引用到互斥体之外 - 为每个线程打开一个单独的'ifstream'。 – 2015-03-13 09:39:59
@AndyBrown使这些变量不稳定是没有意义的。这对线程问题没有帮助。请参阅http://herbsutter.com/2009/01/12/effective-concurrency-volatile-vs-volatile/进行深入解释。 – Jens 2015-03-13 10:32:08