Reputation: 7418
I am reading a .csv file using multiple threads. Each thread reads a part of the .csv file, eg. thread1 reads from line:214
to line:359
.
CSVReader reader1("C:\\file.csv", 214, 359);
During reading process, the data fields are stored in a vector instance.
data[i].push_back(data_field);
In main function, the codes are like below:
CSVReader reader1("C:\\file.csv", 214, 359);
CSVReader reader2("C:\\file.csv", 360, 517);
thread t1(&CSVReader::read_range, reader1);
thread t2(&CSVReader::read_range, reader2);
t1.join();
t2.join();
vector<vector<string>> temp_data = reader1.get_data(); // Here I have the problem
Ideally, reader1.get_data()
should return the data between line:214
and line:359
. But when I look into temp_data
, I found it is not changed at all.
May I know what am I wrong? And how can I fix it?
Upvotes: 1
Views: 75
Reputation: 171413
When you create the threads you pass copies of reader1
and reader2
, so the copies are modified not the original objects. That means the data are added to the copies, and the original objects are unchanged. To pass them by reference use std::ref(reader1)
and std::ref(reader2)
.
If your CSVReader::read_range
function takes a reference your code should not compile, but some buggy compilers (including Visual C++) accept it.
(N.B. in general you should have shown the definition or at least the signature of CSVReader::read_range
so people don't have to guess what your code does.)
Upvotes: 1