- #include<iostream>
- #include<thread>
- #include<string>
- #include<ctime>
- #include<mutex>
- #include<queue>
- #include<fstream>
- #include<sstream>
- #include<random>
- using namespace std;
- const int queueLenght = 4;
- const int botTimeVal = 1;
- const int topTimeVal = 8;
- string bufor[queueLenght];
- int head = 0;
- int tail = 0;
- int buforState(int head, int tail, int queueLenght) {
- if (head == tail)
- return 0;
- else if (head > tail || (tail > head && abs(head - tail) > 1))
- return -1;
- else if (tail > head && abs(head - tail) > 1 || (head == queueLenght && tail == 0))
- return 1;
- }
- int random_int(int min, int max) {
- static std::mt19937 random_number_engine;
- static std::mutex rng_mtx;
- std::uniform_int_distribution<int> distribution(min, max);
- rng_mtx.lock();
- int retval = distribution(random_number_engine);
- rng_mtx.unlock();
- return retval;
- }
- string addString() {
- std::string temp;
- temp.resize(10);
- for (int i = 0; i < 10; i++) {
- temp[i] = random_int('a', 'z');
- }
- return temp;
- }
- void producent(bool &on,const int queueLenght) {
- while (on)
- {
- int state = buforState(head, tail, queueLenght);
- string tmp = addString();
- if (state == 0 || state == -1)
- {
- bufor[head] = tmp;
- cerr << "Do kolejki dodano element o ID: " << tmp << endl;
- cerr << "HEAD : " << head << endl;
- if (head < queueLenght - 1)
- head++;
- else
- head = 0;
- }
- else if(state == 1) {
- cerr << "Obiekt o ID " << tmp << " nie trafil do kolejki" << endl;
- cerr << "HEAD : " << head << endl;
- }
- this_thread::sleep_for(chrono::seconds(random_int(botTimeVal, topTimeVal)));
- }
- }
- void consument(bool &on, const int queueLenght) {
- ofstream file;
- file.open("dane.txt");
- while (on)
- {
- int state = buforState(head, tail, queueLenght);
- if(state == 1 || state == -1){
- if (file.is_open()) {
- file << bufor[tail] << endl;
- cerr << "Zapisano element o ID : " << bufor[tail]<< endl;
- cerr << "TAIL: " << tail << endl;
- if (tail < queueLenght - 1)
- tail++;
- else
- tail = 0;
- }
- else
- cerr << "Nie udalo sie otworzyc pliku " << endl;
- }
- else if(state == 0){
- cerr << "PUSTO " << endl;
- cerr << "TAIL: " << tail << endl;
- }
- this_thread::sleep_for(chrono::seconds(random_int(botTimeVal, topTimeVal)));
- }
- file.close();
- }
- int main() {
- srand(time(NULL));
- bool isOn = true;
- vector<thread> thread_vec;
- thread consument(consument, ref(isOn), queueLenght);
- thread_vec.push_back(move(consument));
- thread producent(producent, ref(isOn), queueLenght);
- thread_vec.push_back(move(producent));
- getchar();
- isOn = false;
- for (auto &t : thread_vec) {
- t.join();
- }
- system("pause");
- return 0;
- }