Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <queue>
- #include <atomic>
- #include "factor.h"
- using namespace std;
- const int THREAD_COUNT = 4;
- vector<atomic_bool> working(THREAD_COUNT);
- vector<uint64_t> now_processing(THREAD_COUNT);
- vector<thread> tp(THREAD_COUNT);
- queue<uint64_t> values;
- mutex out;
- vector<mutex> mutex_thread(THREAD_COUNT);
- vector<condition_variable> cond_thread(THREAD_COUNT);
- void sendToThread(uint64_t x)
- {
- cout << "Send To Thread" << endl;
- for (int i = 0; i < THREAD_COUNT; i++)
- {
- if (!working[i])
- {
- now_processing[i] = x;
- working[i] = true;
- cond_thread[i].notify_one();
- break;
- }
- }
- }
- bool isAvaliableThread()
- {
- bool out = false;
- for (int i = 0; i < THREAD_COUNT; i++)
- {
- if (!working[i])
- {
- out = true;
- break;
- }
- }
- return out;
- }
- int main()
- {
- string in_file, out_file;
- in_file = "input.txt";
- out_file = "output.txt";
- ifstream fin(in_file);
- ofstream fout(out_file);
- for (int i = 0; i < THREAD_COUNT; i++)
- {
- working[i] = false;
- now_processing[i] = 0;
- }
- vector<factor> fact(THREAD_COUNT);
- for (int i = 0; i < THREAD_COUNT; i++)
- {
- tp[i] = thread([&]()
- {
- int num = i;
- cout << num << endl;
- while (true)
- {
- unique_lock<mutex> pause(mutex_thread[num]);
- cond_thread[num].wait(pause);
- cout << "Start: " << num << endl;
- uint64_t input = now_processing[num];
- fact[num].createFactor(input);
- out.lock();
- fout << fact[num].getString() << endl;
- out.unlock();
- cout << "Finish: " << num << endl;
- working[num] = false;
- }
- });
- }
- uint64_t in;
- while (!fin.eof())
- {
- fin >> in;
- while (!isAvaliableThread())
- {
- this_thread::sleep_for(chrono::milliseconds(10));
- //cout << "No avaliable thread" << endl;
- }
- sendToThread(in);
- }
- for (int i = 0; i < THREAD_COUNT; i++)
- {
- tp[i].join();
- }
- fin.close();
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement