C++多线程同时读同一文件
#include <thread>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <chrono>
using namespace std;
//读文件的函数
void thread_read_file(int tid, const string& file_path)
{
//tid是指线程序号
ifstream file(file_path.c_str(), ios::in); //ios::in表示以输入的方式打开一个 文件,并从里面读取数据
if (!file.good()) { //file.good() 是判断文件是否正常,这是文件流的一个函数,当文件出错时进行此循环
stringstream ss; //<sstream>
ss << "Thread " << tid << " failed to open file: " << file_path << "\n";
cout << ss.str();
return;
}
int pos;
if (tid == 0) pos = 0;
else pos = tid * 10;
file.seekg(pos, ios::beg);
/*
* seekg 对输入文件定位(seek—寻找,g—get),有两个参数:
* 第一个:表示偏移量,可正可负,正表示向后,负表示向前
* 第二个:偏移的基地址,可以是:
* ios::beg 输入流的开始
* ios::cur 输入流的当前位置
* ios::end 输入流的结束
*/
string line;
getline(file, line); //读文件file的内容存入line中
stringstream ss;
ss << "Thread " << tid << ", pos=" << pos << ": " << line << endl;
cout << ss.str();
}
void test_detach(const string& file_path)
{
for (int i = 0; i < 10; ++i) {
//std::thread th = thread (thread_read_file, i, file_path);—和下面一样的
std::thread th(thread_read_file, i, file_path);//生成多线程,std::thread构造函数 在 #include<thread> 头文件中声明
//i和file_path是thread_read_file的参数,i是指线程号
th.detach();
}
}
//void test_join(const string& file_path)
//{
// vector<std::thread> vec_threads; //线程型数组vec_threads
// for (int i = 0; i < 10; ++i) {
// std::thread th(thread_read_file, i, file_path);
//
// //添加一个新元素到结束的容器。该元件是构成在就地,即没有复制或移动操作进行。
// //std::move函数可以以非常简单的方式将左值引用转换为右值引用
// vec_threads.emplace_back(std::move(th)); // push_back() is also OK
// }
//
// auto it = vec_threads.begin();
// for (; it != vec_threads.end(); ++it) {
// (*it).join(); //相当于将动态数组里的变量(线程)全设置成join
// }
//}
int main()
{
string file_path = "./1.txt";
test_detach(file_path);
//表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU,根据线程需求,等待若干时间。
std::this_thread::sleep_for(std::chrono::seconds(1)); // wait for detached threads done,std::chrono处理时间的类
//test_join(file_path);
//test_detach(file_path);
return 0;
}