- Examples
Examples for using locks in the scope of concurrency in C++.
We'll cover the following...
Example 1
Press + to interact
//lockGuard.cpp#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 workstd::this_thread::sleep_for(std::chrono::milliseconds(200));// end workstd::lock_guard<std::mutex> myLock(coutMutex);std::cout << name << ": " << "Work " << i << " done !!!" << std::endl;}}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;}
Explanation
-
The program has six worker-threads (lines 36 - 41). Each worker-thread executes the function object
Worker
. -
Worker
has three work packages. Before each work package, the worker sleeps 1/5 second ...