class Locker{
mutex &m_mtx;
public:
Locker(mutex& mtx) : m_mtx{mtx}{m_mtx.lock();}
~Locker(){m_mtx.unlock();}
};
mutex mtx;
int globalOutput = 0;
void sum(const vector<int>& vect, int start, int end)
{
for(auto i = vect.begin() + start; i != vect.begin() + end; ++i)
{
Locker{mtx};
globalOutput+= *i;
}
}
int main()
{
const vector<int> vct(500, 2);
thread th1(&sum, vct, 0, 250);
thread th2(&sum, vct, 250, 500);
th1.join();
th2.join();
std::cout << globalOutput;
}
I used a custom mutex class to synchronize two threads that calculate the sum of 500 items having the value 2.
Do you know of another way to sync threads? Share knowledge, thank you!