Advertisement
nex036ara

threads

Mar 15th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include<iostream>
  2. #include<thread>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. typedef vector<double>::const_iterator ci;
  7. void f(ci begin, ci end, double& zbir);
  8.  
  9. int main() {
  10. vector<double>v = {10,20,30,40,50};
  11. double zbir1; //ukupan zbir
  12. int n;
  13. cout<<"unesi broj niti: "<<endl;
  14. cin>>n;
  15.  
  16. ci begin = v.begin();
  17. ci end = v.begin() + (v.size())/n;
  18.  
  19.  
  20. thread a[n]; //niz thread-ova
  21. double zbir[n];
  22.  
  23. //inicijalizacija niza za sume
  24. for(int k=0; k<n;k++) {
  25.     zbir[k] = 0;
  26.     }
  27.  
  28.  
  29. for(int j=0; j<n-1; ++j) {
  30.     a[j]= thread(f,begin,end,ref(zbir[j]));
  31.     begin = end;
  32.     end = begin+  ( (v.size())/n );
  33.     zbir1+=zbir[j];
  34.     }
  35. a[n] = thread(f,begin,end,ref(zbir[n-1]));
  36. zbir1+=zbir[n-1];
  37.  
  38. for(int s=0; s<n; s++) {
  39.     a[s].join();
  40.     }
  41. cout << "ukupno=" << zbir1<< endl;
  42. }
  43.  
  44. void f(ci begin, ci end, double& zbir){
  45.     ci it;
  46.     for(it=begin; it!=end; ++it) {
  47.         zbir+= *it;
  48.        }
  49.  
  50.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement