Posts

Showing posts from September, 2019

C++ Guidelines for Multithreaded System

Image
Mutithreading è Parallelism è  Achieve concurrency. Below are some of the guidelines to follow for building C++ Multithreaded system. Ø std::thread function arguments are pass by value by default. Thread function arguments are pass by value by default. So, if you want the change to be persisted in the arguments passed in , then pass them by reference using std::ref(). Ø Protect shared data or resource using critical section.     In a multithreaded environment if there are more than one thread sharing the resource/data then often it results in a undefined behaviour if the resource/shared data is not protected using synchronise mechanism. So, the shared resource/data must be protected with std::mutex . Ø Release lock after critical section. If a thread T1 acquires lock (mutex.lock()) before entering critical section and forgets to unlock(mutex.unlock()) then all the other threads will be blocked indefinitely and the program might hang because thread T1 gets hol

Declaring const_iterator vs declaring an iterator const

An iterator acts much like a T* pointer.  Declare an iterator const Declaring an iterator const is nothing but declaring a const  pointer which is equivalent to T* const - iterator is not allowed to point to different object, but the data iter points to can be modified.  Lets look at an example below : std::vector<std::string> vecOfStrings; // Push some strings to the vector // Declare an iterator const const std::vector<string>:: iterator iter; // iter acts like T* const , const pointer iter = vecOfStrings.begin(); *iter = "newValue"; // Ok, changes the value what iter points to. ++iter; // Compilation error , iter is const Declare an const_iterator Declaring an const_iterator is nothing but declaring an pointer to const object which is equivalent to const T* - Iterator can point to different object but modifying the data will throw an compilation error. Let's look at an example below : std::