Posts

Showing posts from 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::

Times when compiler refuses to generate default functions.

Generally C++ compiler generates default functions like Constructor, Copy Constructor, Copy Assignment operator and Destructor if not defined. But there are some cases when compiler also refuses to generate these functions. Consider the below example : name  is a reference and age  is a const T. template<typename T> class PersonObject { public: // this ctor no longer takes a const name, because name // is now a reference-to-non-const string. The char* constructor // is gone, because we must have a string to refer to. NamedObject(std::string& name, const T& age); ... // as above, assume no // operator= is declared private: std::string & name; // this is now a reference const T age ; // this is now const }; Now consider what should happen here: string person1("Tom"); string person2("Mike"); PersonObject<int> p1 (person1, 24); PersonObject<int> p2 (person2, 30); p1 = p2;   // What should happen to the data