#include #include #include #include #include #include #include #include using namespace std; string addString() { std::string temp; temp.resize(10); for (int i = 0; i < 10; i++) { temp[i] = rand() % ('z' - 'a' + 1) + 'a'; } return temp; } void producent(bool &on , queue &vec, const int queueLenght) { while (on) { string tmp = addString(); if (vec.size() < queueLenght){ vec.push(tmp); cerr << tmp << endl; } else cerr << "Obiekt o ID " << tmp << " nie trafil do kolejki" << endl; this_thread::sleep_for(chrono::seconds(1)); } } void consument(bool &on, queue &vec, const int queueLenght, ofstream &file) { while (on) { if (!vec.empty()) { if (file.is_open()){ file << vec.front() << endl; cerr << "Zapisano element o ID : " << vec.front() << endl; vec.pop(); this_thread::sleep_for(chrono::seconds(1)); } } } file.close(); } int main() { srand(time(NULL)); bool isOn = true; const int queueLenght = 10; int noCons = 2; int noProd = 2; queue bufor; vector thread_vec_c; vector thread_vec_p; for (int i = 0; i < noCons; i++) { ofstream file; thread::id ID = this_thread::get_id(); stringstream ss; ss << ID; string mystring = ss.str(); string mystringtxt = mystring + ".txt"; file.open(mystringtxt); thread tmp(consument , ref(isOn), ref(bufor), queueLenght, ref(file)); thread_vec_c.push_back(move(tmp)); } for (int i = 0; i < noProd; i++) { thread tmp(producent, ref(isOn), ref(bufor), queueLenght); thread_vec_p.push_back(move(tmp)); } getchar(); isOn = false; for (auto &t : thread_vec_p) { t.join(); } for (auto &t : thread_vec_c) { t.join(); } system("pause"); return 0; }