- Solutions

The solutions to the exercises in the previous lesson. Here you can test the techniques you learned.

We'll cover the following...

Solution 1

Press + to interact
//threadHardwareConcurrency.cpp
#include <chrono>
#include <iostream>
#include <thread>
class Sleeper{
public:
Sleeper(int& i_, int m):i{i_}, milli(m){};
void operator() (int k){
for (unsigned int j= 0; j <= 5; ++j){
std::this_thread::sleep_for(std::chrono::milliseconds(milli));
i += k;
}
}
private:
int& i;
int milli;
};
int main(){
std::cout << std::endl;
for (unsigned int i=0; i <= 20; ++i){
int valSleeper= 1000;
std::thread t(Sleeper(valSleeper, (i*50)), 5);
t.detach();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "valSleeper = " << valSleeper << std::endl;
}
std::cout << std::endl;
}

Explanation

  • Although the solution seems simple, it has one significant issue. ...

Access this course and 1400+ top-rated courses and projects.