Search⌘ K
AI Features

- Exercises

Explore exercises focused on multithreading in C++. Learn to apply suitable locking mechanisms like unique_lock and lock_guard to prevent data races. Understand how to safely manage shared data structures such as maps during concurrent access. This lesson guides you to implement thread synchronization effectively while solving practical programming challenges.

We'll cover the following...

Task 1

  • Adjust the program below by using a suitable lock: std::unique_lock or std::lock_guard.

You should not explicitly use a mutex.

C++
#include <chrono>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
std::mutex coutMutex;
class Worker{
public:
explicit Worker(const std::string& n):name(n){};
void operator() (){
for (int i= 1; i <= 3; ++i){
// begin work
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// end work
//coutMutex.lock();
std::cout << name << ": " << "Work " << i << " done !!!" << std::endl;
//coutMutex.unlock();
}
}
private:
std::string name;
};
int main(){
std::cout << std::endl;
std::cout << "Boss: Let's start working." << "\n\n";
std::thread herb= std::thread(Worker("Herb"));
std::thread andrei= std::thread(Worker(" Andrei"));
std::thread scott= std::thread(Worker(" Scott"));
std::thread bjarne= std::thread(Worker(" Bjarne"));
std::thread andrew= std::thread(Worker(" Andrew"));
std::thread david= std::thread(Worker(" David"));
herb.join();
andrei.join();
scott.join();
bjarne.join();
andrew.join();
david.join();
std::cout << "\n" << "Boss: Let's go home." << std::endl;
std::cout << std::endl;
}

Task 2

Implement a count-down counter from 10 – 0. It should count down in seconds steps.

C++
#include <iostream>
int main() {
// your code goes here
std::cout << "Hello World";
return 0;
}
...