Advertisement
obernardovieira

threads, mutex and condition variable (the fastest thread)

Mar 21st, 2016
370
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. //in Linux you should compile using
  2. //g++ -std=c++11 file_name.cpp -pthread -o destination_file_name && ./destination_file_name
  3.  
  4. #include <iostream>
  5. #include <thread>
  6. #include <mutex>
  7. #include <condition_variable>
  8. #include <chrono>
  9.  
  10. std::mutex mtx;
  11. std::condition_variable cv;
  12.  
  13. //thanks to
  14. //http://falsinsoft.blogspot.pt/2014/05/set-console-cursor-position-in-windows.html
  15. void setCursorPos(int XPos, int YPos)//linux version
  16. {
  17.     printf("\033[%d;%dH", YPos+1, XPos+1);
  18. }
  19.  
  20. int main() {
  21.  
  22.     int i;
  23.     std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
  24.  
  25.     for(i = 0; i < 10; i++) {
  26.  
  27.         std::thread([](int position) {
  28.  
  29.             for(int x = 0; x < 10000; x++) {
  30.                 mtx.lock();
  31.                 setCursorPos(position, position);
  32.                 std::cout << "X[" << position << "] -> " << x << std::endl;
  33.                 if(x == 9999) {
  34.                     cv.notify_one();
  35.                 }
  36.                 mtx.unlock();
  37.             }
  38.  
  39.         }, i).detach();
  40.  
  41.     }
  42.  
  43.     std::unique_lock<std::mutex> lck(mtx);
  44.     cv.wait(lck);
  45.  
  46.     std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
  47.     std::cout << "First thread took "
  48.               << std::chrono::duration_cast<std::chrono::seconds>(end - start).count()
  49.               << "s.\n";
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement