Advertisement
Guest User

5.4 strange

a guest
Jan 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <thread>
  4. #include <mutex>
  5. #include <condition_variable>
  6. #include <queue>
  7. #include <atomic>
  8. #include "factor.h"
  9.  
  10. using namespace std;
  11.  
  12. const int THREAD_COUNT = 4;
  13.  
  14. vector<atomic_bool> working(THREAD_COUNT);
  15. vector<uint64_t> now_processing(THREAD_COUNT);
  16. vector<thread> tp(THREAD_COUNT);
  17. queue<uint64_t> values;
  18.  
  19. mutex out;
  20. vector<mutex> mutex_thread(THREAD_COUNT);
  21. vector<condition_variable> cond_thread(THREAD_COUNT);
  22.  
  23. void sendToThread(uint64_t x)
  24. {
  25. cout << "Send To Thread" << endl;
  26. for (int i = 0; i < THREAD_COUNT; i++)
  27. {
  28. if (!working[i])
  29. {
  30. now_processing[i] = x;
  31. working[i] = true;
  32. cond_thread[i].notify_one();
  33. break;
  34. }
  35. }
  36. }
  37.  
  38. bool isAvaliableThread()
  39. {
  40. bool out = false;
  41. for (int i = 0; i < THREAD_COUNT; i++)
  42. {
  43. if (!working[i])
  44. {
  45. out = true;
  46. break;
  47. }
  48. }
  49. return out;
  50. }
  51.  
  52. int main()
  53. {
  54.  
  55. string in_file, out_file;
  56.  
  57. in_file = "input.txt";
  58. out_file = "output.txt";
  59.  
  60. ifstream fin(in_file);
  61. ofstream fout(out_file);
  62.  
  63. for (int i = 0; i < THREAD_COUNT; i++)
  64. {
  65. working[i] = false;
  66. now_processing[i] = 0;
  67. }
  68.  
  69. vector<factor> fact(THREAD_COUNT);
  70.  
  71.  
  72. for (int i = 0; i < THREAD_COUNT; i++)
  73. {
  74. tp[i] = thread([&]()
  75. {
  76. int num = i;
  77. cout << num << endl;
  78. while (true)
  79. {
  80. unique_lock<mutex> pause(mutex_thread[num]);
  81. cond_thread[num].wait(pause);
  82.  
  83. cout << "Start: " << num << endl;
  84. uint64_t input = now_processing[num];
  85.  
  86. fact[num].createFactor(input);
  87.  
  88. out.lock();
  89. fout << fact[num].getString() << endl;
  90. out.unlock();
  91.  
  92. cout << "Finish: " << num << endl;
  93. working[num] = false;
  94. }
  95. });
  96. }
  97.  
  98. uint64_t in;
  99. while (!fin.eof())
  100. {
  101. fin >> in;
  102. while (!isAvaliableThread())
  103. {
  104. this_thread::sleep_for(chrono::milliseconds(10));
  105. //cout << "No avaliable thread" << endl;
  106. }
  107. sendToThread(in);
  108. }
  109.  
  110. for (int i = 0; i < THREAD_COUNT; i++)
  111. {
  112. tp[i].join();
  113. }
  114.  
  115. fin.close();
  116. fout.close();
  117.  
  118. return 0;
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement