My program reads in two input files and alternates writing lines to an output file. I have it so it writes in the right order (first file, then second , then first again, ....) but the problem is it writes the last character in each file twice at the end.
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
int turn = 1;
void print_line(ifstream * in_stream, ofstream * out_stream, int t);
int main(int argc, const char * argv[]){
ifstream input_file_1;
ifstream input_file_2;
ofstream output_file;
input_file_1.open("input_1");
input_file_2.open("input_2");
output_file.open("output");
if (input_file_1.fail() || input_file_2.fail() || output_file.fail()) {
cout << "Error while opening the input files\n";
exit(EXIT_FAILURE);
}
else{
thread input1 (print_line, &input_file_1, &output_file, 1);
thread input2 (print_line, &input_file_2, &output_file, 2);
input1.join();
input2.join();
}
input_file_1.close();
input_file_2.close();
output_file.close();
return 0;
}
void print_line(ifstream * in_stream, ofstream * out_stream, int t){
char temp;
while (!in_stream->eof()) {
mtx.lock();
if (turn == t) {
*in_stream>>temp;
*out_stream<<temp;
if (turn == 1) {
turn = 2;
}
else{
turn = 1;
}
}
mtx.unlock();
}
}
input 1
a
c
e
input 2
b
d
f
output
abcdefef
I don't know why it writes the last character again, also is there a better way to do the ordering part using threads, I understand that a mutex is used to make sure both threads don't write at the same time, however how can I guarantee that thread one executes before thread 2 and make sure it keeps alternating?
Thanks