Friday, January 12, 2024
National Youth Day - here's is a clarion call to the engineers of Bharat - wake up and embrace Sanskrit...
Sunday, January 7, 2024
Latches in C++ 20 concurrency - just like the CountdownLatch of Java concurrency package...
Multithreaded programming is inherently difficult. One of the reasons is that we can't have control over how a thread will start and finish - in which order - it all depends upon the thread scheduling algorithm of the OS. This makes the reproduction of test cases difficult. Moreover, there are race conditions and deadlocks.
When I was teaching the Countdown latch - a thread synchronization technique used in the Java Concurrency package, there was none like that available in C++. I am happy to see that the concept of latch is introduced in C++20.
So...
What is a Latch in C++?
- A synchronization primitive was introduced in C++20.
- It allows one or more threads to wait for a certain number of operations to complete before proceeding.
- Acts like a countdown counter that blocks threads until it reaches zero.
/*
* Student.h
*
* Created on: Jan 7, 2024
* Author: som
*/
#ifndef STUDENT_H_
#define STUDENT_H_
#include <iostream>
#include <string>
#include <thread>
#include <latch>
#include <chrono>
#include <vector>
#include <syncstream> // For thread-safe console output
#include <format> // For C++20 string formatting
class Student {
private:
std::string name;
int timeToFinish;
public:
Student(std::string name, int finish)
: name(std::move(name)),
timeToFinish(finish) {}
virtual ~Student() = default;
void task(std::latch& l){
auto now = std::chrono::system_clock::now();
// Locate the current system timezone and convert UTC to local time
auto local_time = std::chrono::current_zone()->to_local(now);
std::osyncstream(std::cout)
<< name << " is Starting the task at "
<< std::format("{:%F %T}", local_time) << "\n";
// 4. Simulate performing the task
std::this_thread::sleep_for(std::chrono::milliseconds(timeToFinish));
std::osyncstream(std::cout) << name << " finished the task.\n";
l.count_down();
}
};
#endif /* STUDENT_H_ */
/*
* classETC.h
*
* Created on: Jan 7, 2024
* Author: som
*/
#ifndef CLASSETC_H_
#define CLASSETC_H_
#include "Student.h"
class classETC {
public:
Student ridit {"Ridit", 1000};
Student ishan {"Ishan", 3000};
Student rajdeep {"Rajdeep", 900};
classETC() = default;
virtual ~classETC() = default;
auto giveTaskToStudent(std::latch& l){
std::vector<std::jthread> workers;
workers.reserve(3);
// Emplace threads directly into the vector
workers.emplace_back(&Student::task, &this->ridit, std::ref(l));
workers.emplace_back(&Student::task, &this->ishan, std::ref(l));
workers.emplace_back(&Student::task, &this->rajdeep, std::ref(l));
std::cout<<"Teacher is waiting for all the students to finish their task"<<std::endl;
l.wait();
std::cout<<"All students submitted their task... Teacher is leaving the class"<<std::endl;
return workers; // Named Return Value Optimization (NRVO) handles this cleanly
}
};
#endif /* CLASSETC_H_ */
Main:
// ==========================================
// Main Method
// ==========================================
#include "classETC.h"
int main() {
// Print C++ standard validation
std::cout << "C++ Version: ";
if (__cplusplus == 202101L) std::cout << "C++23\n";
else if (__cplusplus == 202002L) std::cout << "C++20\n";
else std::cout << "Other/Experimental (" << __cplusplus << ")\n";
std::cout << "-------------------------------------------\n";
std::latch l(3);
classETC etc;
// FIX: Capturing the threads in main() preserves their lifetimes.
// They will execute concurrently and automatically join when main() ends.
auto threads = etc.giveTaskToStudent(l);
return 0;
}
Explanation of the code:
For your reference, here's my son Ridit on Java CountdownLatch.
#Enjoy
Wednesday, December 6, 2023
Why I taught my son Design Pattern even before Data Structure...
Let me give you an example.
You know callback mechanism, observer pattern, and event listener pattern - all do kind of the same work - notify some objects when a specific event occurs. However, without the knowledge of design patterns, we will simply try to understand this phenomenon from just a programmer's point of view - and definitely, we will miss the big picture behind writing such kinds of object-oriented code.
I remember, when I studied the command routing architecture of Visual C++/MFC source code, I tried to map it with the Gang of Four design patterns and found out that this architecture uses two common design patterns at the same time - Command pattern and Chain of responsibility pattern.
Studying design patterns helps to decipher object-oriented code more like a professional - and not like a novice programmer.
It helps to figure out the source code not only from what and how's point of view, but also from Why's point of view. We can explain why a piece of code has been or should be written in a particular way.
Understanding the Why's is very essential for a software developer.
Let me tell you about my journey in NOKIA India in 2007 using Symbian S60 C++ framework.
There is a concept in Symbian called a two-phase constructor. I asked people about the Why's point of view. Nobody gave me the answer - everybody said this is the norm in Symbian. While breaking my head about this "why", I went to Japan and then realized the reason for such a two-phase constructor - to avoid the exception during constructor in case of low memory. Because in the earlier days of mobile phones, there was limited memory and moreover there were no template concepts in C++. Hence there was no smart pointer. This led me to study Boost pointer in Japan in 2008 and voila, in 2009 Boost library became a part of the standard C++ library.
In concisely, to get the big picture of any object-oriented code structure, it's important to know Design Patterns. It clarifies many questions - particularly why a piece of code should be written in a specific manner.
Here's the evolutionary journey of Ridit, my son and a young Computer Scientist of Bharat - vis-a-vis Design Pattern...
My bragging right - as a Guru of my son...
State Pattern in Java : 8 yrs old
State pattern in C++ : 11 yrs old
State pattern in Python : 12 yrs old
import FreeCAD as App
# Create a new document
doc = App.newDocument()
# Create a composite container (e.g., Part::Compound or App::Part)
composite = doc.addObject("App::Part", "CompositePart")
# Create child objects
box = doc.addObject("Part::Box", "Box")
sphere = doc.addObject("Part::Sphere", "Sphere")
# Set positions for better visualization
box.Placement.Base = App.Vector(0, 0, 0)
sphere.Placement.Base = App.Vector(5, 0, 0)
# Add child objects to the composite container
composite.addObject(box)
composite.addObject(sphere)
# Recompute the document to reflect changes
doc.recompute()
print("Composite Part created with Box and Sphere as children.")
Thursday, November 23, 2023
A baby step in the wonderland of Quantum Computing...
I am of the opinion that there is no age limit for trying out new things in life.
I consider myself a perpetual student.
Today will be a memorable day for me.
I have started my journey into the world of Quantum Computing.
From almost no knowledge in college (even didn't know how to start the Basic development environment) to taking concrete steps to pick up Quantum Computing - it's a checkered journey - a lot of midnight oil is burnt - a lot of frustration, many times it became unbearable, traveled many places - but one thing always drove me - the intrinsic motivation - never did anything just for monetary gain - remained a perpetual student. I started my software journey when there was no Google. it was naturally challenging. but worth the effort...
So, here we go - my first coding in the area of Quantum Programming.
Here is the output
Output counts: {'1': 464, '0': 536}
And here goes another simple program of a basic entangler.
Enjoy...
Here goes the output of the above piece of code
Output counts: {'00': 489, '11': 511}
To start something absolutely new is challenging yet satisfying. I am always motivated by intrinsic motivation. Hence the joy of learning is still there in me, a perpetual student…
Thursday, November 16, 2023
Engineers of Bharat - wakeup - know WhoWeAre - part II
Here's the clarion call to all of the engineers of Bharat - embrace #Sanskrit and go back to your roots. Know your real worth.
Till to date, scientists are baffled at how the Tithis are so accurately calculated in ancient Bharat.
Read the following article.
Our Vedas were written more than 15000 years ago.
Isn't it amazing?
We were invaded by Muslims and then the British - but our only defeat has become true when an inferiority complex was injected into us.
Come ON... the Humans of Bharat...
please ...
wake up and reclaim who you are...
Read... Read...
Saturday, September 2, 2023
Iterator Design Pattern in Python...
Iterator design pattern is a behavioral design pattern that lets you access the element of a complex data structure - a collection class - without the knowledge of the internal structure of the elements it is accessing.
To create an iterator in Python, there are two abstract classes from the built-in `collections` module - Iterable, and Iterator. We need to implement the
`__iter__()` method in the iterated object (collection), and the `__next__ ()` method in the iterator.
The concrete class that implements the Iterator class provides various means of different ways of iteration through the collection class.
In our example, AlphabeticalOrderIterator is such a class that has provided forward and reverse ways of iteration. In this example, the WordsCollection class represents a collection of words and implements the Iterable interface.
The source code is as follows:
from collections.abc import Iterator, Iterable
from typing import Any, List
class WordsCollection(Iterable):
def __init__(self, collection: List[Any]=[]):
self._collection = collection
def __iter__(self):
return AlphabeticalOrderIterator(self._collection)
def get_reverse_iterator(self):
return AlphabeticalOrderIterator(self._collection, True)
def add_item(self, item:Any):
self._collection.append(item)
class AlphabeticalOrderIterator(Iterator):
_position = None
_reverse = False
def __init__(self, collection : WordsCollection, reverse: bool = False):
self._collection = collection
self._reverse = reverse
self._position = -1 if self._reverse else 0
def __next__(self):
try:
value = self._collection[self._position]
self._position += -1 if self._reverse else 1
except IndexError:
raise StopIteration()
return value
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
wordsCollection = WordsCollection()
wordsCollection.add_item("Som")
wordsCollection.add_item("Reema")
wordsCollection.add_item("Ridit")
print("Forward traversal:")
print("\n".join(wordsCollection))
print("")
print("Reverse traversal:")
print("\n".join(wordsCollection.get_reverse_iterator()), end="")
If we run the above program the output will be as follows:
Forward traversal:
Som
Reema
Ridit
Reverse traversal:
Ridit
Reema
Som
Friday, September 1, 2023
Prototype Design Pattern in Python...
The prototype design pattern is a creational pattern.
If the creation of an object is a very costly affair and we already have a similar kind of object, instead of creating it each time we need it, we use the clone of the object that is already there.
Suppose, there is a large object with many attributes whose data we read from a database. We need to modify that data multiple times in our program. So instead of creating the object each time by reading from the database, we tend to keep a prototype object - we clone it, and then work on it.
In Python, there is a module called copy which has two methods - copy() and deepcopy(). The first one is for the shallow copy and the second one is for the deepcopy.
Here is the source code of an example of the Prototype design pattern.
from abc import ABC, abstractmethod
import copy
class Person(ABC):
def __init__(self, name):
self._name = name
def set_name(self, name):
self._name = name
def get_name(self):
return self._name
@abstractmethod
def clone(self):
pass
@abstractmethod
def display(self):
pass
class Teacher(Person):
def __init__(self, name, course):
super().__init__(name)
self._course = course
def set_course(self, course):
self._course = course
def get_course(self):
return self._course
def display(self):
print("\nTeacher's name : ", self._name, "\n")
print("\nHe teaches : ", self.get_course())
def clone(self):
return copy.deepcopy(self)
class Student(Person):
def __init__(self, name, teacher):
super().__init__(name)
self._teacher = teacher
def display(self):
print("\n Student's name : ", self.get_name())
print("\n Taught by : ", self._teacher.get_name())
print("\n Enrolled in the subject : ", self._teacher.get_course())
def clone(self):
return copy.deepcopy(self)
if __name__ == '__main__':
teacher = Teacher('Som', "Python Design Patttern")
teacherClone1 = teacher.clone()
student = Student ("Ridit", teacherClone1)
studentClone1 = student.clone()
teacherClone1.set_course("DSA")
teacherClone1.display()
studentClone1.display()
If we run the above piece of code the result will be as follows:
Teacher's name : Som
He teaches : Python Design Patttern
Teacher's name : Som
He teaches : DSA
Student's name : Ridit
Taught by : Som
Enrolled in the subject : Python Design Patttern
As you can see, we have used deep copy here.




.png)