1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <time.h>
#include <stdio.h>
using namespace std;
std::mutex mutexS, mutexP;
int result=0;
void SUM(int &sum, int x, unsigned id)
{
std::lock_guard<std::mutex> guard(mutexS);
sum += x;
printf(" %d",sum);
}
void MINUS(int &sum, int x, unsigned id)
{
std::lock_guard<std::mutex> guard(mutexS);
sum -= x;
printf(" %d",sum);
}
// number X times
void PARALEL_SUM( int x, int pN)
{
std::lock_guard<std::mutex> guard(mutexP);
vector<thread> vthread;
printf("\nParalel SUM:");
for (unsigned i=0; i<pN; ++i)
{
vthread.push_back(thread(SUM, ref(result), x, i) );
}
for_each (vthread.begin(),vthread.end(), mem_fn(&std::thread::join));
}
void PARALEL_MINUS( int x, int pN)
{
std::lock_guard<std::mutex> guard(mutexP);
vector<thread> vthreadMinus;
printf("\nParalel MINUS:");
for (unsigned i=0; i<pN; ++i)
{
vthreadMinus.push_back(thread(MINUS, ref(result), x, i) );
}
for_each (vthreadMinus.begin(),vthreadMinus.end(), mem_fn(&std::thread::join));
}
void SERIAL_SUM( int x, int pN)
{
int sum=0;
printf("\nSerial SUM:");
for (unsigned i=0; i<pN; ++i)
{
sum += x;
printf(" %d",sum);
}
}
int main()
{
int x, factor;
cout<<"\nStart\n";
cout<<"Enter x then Factor:";
//cin>>x;cin>>factor;
x=1;factor=4;
thread tSUM(PARALEL_SUM, x, factor);
thread tMIN(PARALEL_MINUS, x, factor);
tSUM.join();
tMIN.join();
SERIAL_SUM (x, factor);
cout<<"\nEnd\n";
}
|