0

I am playing with threads but I don't know why this code doesn't work properly. It has to read two files(the names of the files come from keyboard) and then show the contents in the console. Could you tell me where is the problem?

#include<iostream>
#include<fstream>
#include<thread>
#include<string>
#include<vector>
using namespace std;
mutex mtx;
class eu
{
    string filename;
    string buffer;
public:
    eu() {};
    void citire(string filename)
    {
        this->filename = filename;
        ifstream f(filename);
        while (f.eof())
        {
            string ceva;
            f >> ceva;
            buffer = buffer + ceva;
        }
        f.close();

    }
    /*void operator()()                   it doesn't work either in this way
    {
        this->citire(filename);
    }*/

    friend ostream &operator<<(ostream& os, eu&n);

    //~eu();
};

ostream& operator<<(ostream& os, eu&n)
{
    os << n.buffer;
    return os;
}
//threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

int main()
{
    vector<thread>instante;
    string nume;
    eu n;
    for (int i = 0; i <2; i++)
    {
        cin >> nume;
        instante.push_back(thread(&eu::citire, n, nume));
    }
    for (auto& th : instante) th.join();
    cout << n;
}
Dale K
  • 16,372
  • 12
  • 37
  • 62
  • 2
    What doesn't work properly? `while(f.eof())` looks like there is missing a `!`, but that could give you strange results => [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/q/5605125/5105949) – churill Apr 17 '20 at 13:35
  • 2
    If I understand your code correctly each thread runs the `eu::citire` on the _same_ object, which means `buffer = buffer + ceva;` will become a race condition, since both threads try to write to the same variable. There are some points to overthink here, but it's impossible to find an answer if you don't ask a specific question :) – churill Apr 17 '20 at 13:44
  • 1
    the problem is that the thread doesn't call ```eu::citire``` @churill – Teodora Grecu Apr 17 '20 at 15:20
  • But it is called. When I copy-paste and debug this code the debugger will hit the breakpoint in `eu::citire`. (after removing the `mutex mtx;` to make it compile) Why do you think it isn't called? – churill Apr 17 '20 at 18:28
  • My debugger didn’t hit that breakpoint when i tried, but you were right about the race conditio. I used a vector of instances of eu class and Now it works. Thanks for idea @churill – Teodora Grecu Apr 18 '20 at 06:23

0 Answers0