ChrisD
ChrisD

Reputation: 674

How can I write to a single file concurrently?

Suppose I have two files I want to read from. How can I write the file contents of each file to another file concurrently? Currently, I'm reading the contents of each file into a vector and placing locks around the read section, but when I do something similar during the writing process, I am only seeing contents from one of the files in my output file.

I am compiling with g++ -std=c++11 -pthread program_name. Any comments or criticisms welcome.

#include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <vector>

void read(const char *file);
void write(const vector<string> &v);

void read(const char *file) {
    string line;
    vector<string> v;
    ifstream in(file);

    m.lock();
    while(getline(in, line)) {
        v.push_back(line);
    }
    in.close();
    m.unlock();

    write(v);
}

void write(const vector<string> &v) {
    ofstream out("Foo");
    vector<string>::const_iterator it;
    m.lock();
    for(it = v.begin(), it != v.end(); ++it) {
        out << *it << endl;
    }
    out.close();
    m.unlock();
}

int main(int argc, char *argv[]) {
    thread t[2];
    for(int i = 1; i < 3; i++) {
        t[i-1] = thread(read, argv[i]);
    }

    for(int k = 0; k < 2; k++) {
        t[i].join();
    }

     return(0);
}

Upvotes: 0

Views: 572

Answers (1)

Patrick Frey
Patrick Frey

Reputation: 11

You should pass the mode (2nd parameter) to the constructor of ofstream (http://www.cplusplus.com/reference/fstream/ofstream/ofstream/) ofstream out( "Foo", std::ofstream::app)

otherwise the file gets overwritten, every time you call write.

The concurrency is a different issue. Concurrency does not make much sense if your problem consists of parts that are inherently sequential.

Upvotes: 1

Related Questions