mardi 28 janvier 2020

C++ shared_mutex, threads: memory dump while program is running

I'm new to threads and I have to do some multithreading. Below you'll find code so let me explain it a little bit. I have a class Writer that can write to a file and class Reader that can read from a file, of course, many readers can read from the file at the same time but only one Writer can write to file at some moment.

So, I'm using shared_mutex because it lets Readers read from the file at the same time. But when the program is running it stops and it shows me in the console that I have memory dump.

So, I have no idea what's going on. Here is my code:

#include <iostream>
#include <thread>
#include <shared_mutex>
#include <mutex>
#include <fstream>
#include <string>
#include <chrono>
#include <vector>
#include <algorithm>
#include <functional>
#include <time.h>

using namespace std;

int getSeconds() {
    return rand() % 5 + 1;;
}

class Judge {
public:
    shared_mutex decision;
    Judge(){}
};

class Reader {
public:
    string id;
    Reader(string ID) {
        id = ID;
    }
    void Action(fstream &file, shared_mutex &decision) {
        string line;

        this_thread::sleep_for(chrono::seconds(getSeconds()));
        shared_lock<shared_mutex> lock(decision);
        while (getline(file, line));
        lock.unlock();

        if(line.length() < 1) return;
        cout << id + line << endl;
    }
};

class Writer {
public:
    string id;
    Writer(string ID) {
        id = ID;
    }
    void Action(fstream &file, shared_mutex &decision) {
        int number = rand() % 1000 + 1;

        this_thread::sleep_for(chrono::seconds(getSeconds()));
        lock_guard<shared_mutex> lock(decision);
        file << id + to_string(number) << endl;
    }
};

int main()
{
    srand(time(NULL));
    int num = 5;

    vector<thread> threads;
    vector<Writer> writers;
    vector<Reader> readers;
    Judge judge = Judge();
    fstream file("dane.txt", ios::app | ios::in);

    if(file.is_open()) {
        for (int i = 0; i < num; i++)
        {
            string wID = to_string(0) + to_string(i);
            string rID = to_string(1) + to_string(i);
            writers.push_back(Writer(wID));
            readers.push_back(Reader(rID));
        }

        for (int i = 0; i < num; i++){
            threads[i] = thread(&Writer::Action, &writers[i], ref(file), ref(judge.decision));
            threads[i + num] = thread(&Reader::Action, &readers[i], ref(file), ref(judge.decision));
        }

        for(int i = 0; i < num; i++) {
            threads[i].join();
        }
        file.close();
    } else {
        cout << "Couldn't open file: dane.txt!" << endl;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire