今天想写一个多线程读取一个文本文件,需要fstream对象作为函数参数,出现了编译错误,查询了网上很多资料,在此汇总一下。
#include
#include
#include
#include
#include
#include
#include
using namespace std;
boost::mutex mt;
void Print(fstream fr)
{
string sth;
mt.lock();
getline(fr, sth);
cout << sth << endl;
mt.unlock();
}
int main()
{
fstream fr;
fr.open("E:\\test\\theap\\image.txt", ios_base::in);
Print(fr);
th1.join();
th2.join();
return 0;
}
上面的代码编译出错。原因就是fstream 对象没有复制构造函数,因此不能执行复制操作,而函数是实参复制给形参,因此这里就出错。因此,我们必须使用引用的方式传递参数。
子函数修改为:
void Print(fstream& fr)// 此处必须使用引用方式传递参数
{
string sth;
mt.lock();
getline(fr, sth);
cout << sth << endl;
mt.unlock();
}
这样修改后,普通调用就没有问题了!
修改后的完整代码:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
boost::mutex mt;
void Print(fstream& fr)
{
string sth;
mt.lock();
getline(fr, sth);
cout << sth << endl;
mt.unlock();
}
int main()
{
fstream fr;
fr.open("E:\\test\\theap\\image.txt", ios_base::in);
//Print(fr);
boost::thread th1(boost::bind(Print, fr));
boost::thread th2(boost::bind(Print, fr));
th1.join();
th2.join();
return 0;
}
我使用了boost::bind(Print,fr),这里又报错了。具体可参考:http://blog.csdn.net/yuan1164345228/article/details/49176029
std::ref 用于包装按引用传递的值。
std::cref 用于包装按const 引用传递的值。
修改两行代码:
boost::thread th1(boost::bind(Print, boost::ref(fr)));
boost::thread th2(boost::bind(Print, boost::ref(fr)));