Concurrent C++ 11 mutex question (by example programm)

I Have made this programm which takes a global, and a 1st thread

SUMS from 0 to 4 by a PARALEL_SUM ( int x, int pN)

who creates 4 threads of SUM (int &sum, int x)
then concurently the 2nd threas
MINUS back from 4 to 0 by a PARALEL_MINUS( int x, int pN)

who creates 4 threads of MINUS(int &sum, int x)

I have 2 Mutexes. 1st who locks SUM-MINUS both at begining
2nd who locks PARALEL_SUM-PARALEL_MINUS both at begining also

Someone help me undesrtand these 4 results if possible

A)If i dont lock the 2nd ( the 2 Top level thread ) I might get a result like
>Paralel SUM: 1 2 3
>Paralel MINUS: 4 3 2 1 0


B)while if i dboldont lock nothing I might get a result like
>Paralel SUM:
>Paralel MINUS: 1 2 3 4 3 2 1 0


C)If i lock BOTH LEVELS ( all 4 functions ) i get the superb
>Paralel SUM: 1 2 3 4
>Paralel MINUS: 3 2 1 0


D)if i use SINGLE MUTEX for both levels (all 4 funcs) i get NOTHING the programm never ends seems to be blocked

As u see i cant get how exaclty the lock process of mutex works

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";
}


Last edited on
Topic archived. No new replies allowed.