Monday, July 29, 2024

C++ 20 multi threaded programming - the introduction of std::atomic...

Data races in C++ multithreaded applications occur when multiple threads try to access a single data without proper data locking tools like mutex.

Causes of Data Races

  1. Concurrent Reads and Writes: If one thread reads a variable while another writes to it without synchronization, a data race occurs.
  2. Concurrent Writes: If multiple threads write to the same variable concurrently without synchronization, it leads to a data race.
  3. Lack of Synchronization Primitives: Not using mutexes, atomic operations, or other synchronization mechanisms can result in data races.

Data race may cause unpredictable output and even crashes.

For example, look at the below C++ programs.

//============================================================================

// Name : C++20Atomic.cpp

// Author : Som

// Version :

// Copyright : som-itsolutions

// Description : Hello World in C++, Ansi-style

//============================================================================


#include <iostream>

#include <atomic>

#include <thread>


int counter = 0;



void incrementCounter() {

for (int i = 0; i < 10000; ++i) {

counter++;

}

}


int main() {

std::thread t1(incrementCounter);

std::thread t2(incrementCounter);


t1.join();

t2.join();


std::cout << "Final counter value: " << counter << std::endl;


return 0;

}

Here two threads are trying to access a single variable without a proper synchronization technique.

Here is the video in which the program is run in Eclipse.


You can see that as the counter increases, the output is incorrect. This is because we didn't use any thread-safe way to access the variable.

In C++ 20, with the introduction of atomic data, this can be easily handled.

So, now we have changed the simple variable into an atomic variable.

//============================================================================

// Name : C++20Atomic.cpp

// Author : Som

// Version :

// Copyright : som-itsolutions

// Description : Hello World in C++, Ansi-style

//============================================================================


#include <iostream>

#include <thread>

#include <atomic>


std::atomic<int> counter(0);


void incrementCounter() {

for (int i = 0; i < 10000000; ++i) {

counter++;

}

}


int main() {

std::thread t1(incrementCounter);

std::thread t2(incrementCounter);


t1.join();

t2.join();


std::cout << "Final counter value: " << counter << std::endl;


return 0;

}


And voila...

The output result is perfect...



C++ is gradually becoming powerful after a very long period of hibernation. 

Enjoy...

Monday, June 10, 2024

What is a 3D Software Engineer from the POV of career options - fatherhood rocks...

A 3D Software Engineer is a programmer who builds software applications specifically designed for 3D graphics and visualization. They essentially bridge the gap between the artistic world of 3D modelling and the technical world of computer science.

Here's a breakdown of their responsibilities:

Software Development: 

They write code and develop software applications that deal with 3D graphics, like animation tools, modelling software, or rendering engines.

Understanding 3D Concepts: 

They have a deep understanding of 3D graphics and rendering algorithms. This allows them to optimize software for efficient creation and display of 3D visuals.

Problem-Solving: 

They troubleshoot and debug software to ensure it functions smoothly and delivers high-quality results.

Collaboration: 

They often work alongside software development teams and may even collaborate with 3D artists or designers to understand their needs and create effective tools.

Here are some of the industries that employ 3D Software Engineers:

- Video Game Development

- Film and Animation Studios

- Architecture and Engineering

- Medical Visualization

- Scientific Research

- Building software which will be used for developing flight-simulation, rocket and missile simulation, etc

If you're interested in this field, you'll need strong skills in computer science and mathematics, along with a passion for 3D graphics. Expertise in programming languages like C++ or Python and being familiar with 3D software like Maya or Blender would be a big plus.

My son, Ridit is at the juncture of software development and 3D modelling - having expertise in both of these fields.

Here are some of the animations my son Ridit created using Blender...

This is how it started for Ridit - the journey to learn 3D modelling.

And here are some others...

The passage of Time...




The Water Tornado...




The making of a filter coffee maker... (Fusion 360)




Here's his technical blog...

This blog mainly has stories of his journey as a software professional through the maze called software. 

Saturday, June 1, 2024

Bharat's ambitious three-stage nuclear energy program...

Watch...


I am not a Nuclear Energy expert - but these days with the help of Gemini and ChatGPT, we can get the right information easily. This blog post is just to disseminate the good work done by the scientists of Bharat.

I am sure the Bharat that my son will be experiencing - will be much different than what we saw after coming out from the engineering colleges in '90s.

#JaiHind

Let's come to the point...

India's ambitious three-stage nuclear program is a strategic plan for developing nuclear power using domestic uranium and thorium reserves. It was formulated by Homi Bhabha, a renowned physicist in the 1950s. The ultimate goal of this program is to achieve long-term energy security for the country by effectively utilizing its abundant thorium reserves.

Here's a breakdown of the three stages:

Stage 1: Pressurized Heavy Water Reactors (PHWRs)

PHWRs use natural uranium as fuel and heavy water (deuterium oxide) as a moderator and coolant.

These reactors are efficient in extracting energy from uranium because heavy water is a more effective neutron moderator than regular water.

India has successfully built and operated numerous PHWRs, and they currently form the backbone of the country's nuclear power generation.

Stage 2: Fast Breeder Reactors (FBRs)

FBRs are designed to produce more fissile material (plutonium) than they consume.

They achieve this by using plutonium or enriched uranium as fuel and a liquid metal (like sodium) as coolant.

The plutonium produced in FBRs can be used as fuel in further reactors, reducing dependence on mined uranium.

India is actively developing FBR technology, and the Prototype Fast Breeder Reactor (PFBR) at Kalpakkam is a significant milestone in this direction.

Stage 3: Advanced Nuclear Power Systems (Thorium Reactors)

This stage focuses on utilizing India's vast thorium reserves for sustainable energy generation.

Thorium itself is not fissile, but it can be converted into fissile uranium-233, which can be used as fuel in nuclear reactors.

Advanced reactor designs like Advanced Heavy Water Reactors (AHWRs) and Molten Salt Reactors (MSRs) are being explored for efficient thorium utilization.

Significance of the 3-stage program:

India has limited uranium reserves but vast thorium reserves. This program allows India to achieve energy security by effectively using its domestic resources.

FBRs help in plutonium production, reducing reliance on imported fissile material.

Thorium-based reactors offer a sustainable and long-term solution for India's energy needs due to the abundance of thorium.

Challenges:

Developing and deploying advanced reactor technologies like FBRs and thorium reactors is a complex and time-consuming process.

Nuclear safety and waste management are critical concerns that need to be addressed effectively.

Overall, India's three-stage nuclear program is a far-sighted approach to ensuring the country's long-term energy security. It leverages domestic resources and promotes sustainable nuclear power generation.

Friday, May 24, 2024

HMI - Human Machine Interface or Hacker Machine Interface - the vulnerability in the SCADA system - the entry of Rust...

Economic nuke on America - the Baltimore Bridge Collapse ...

Why we must upgrade our critical systems from legacy software which was not written keeping cyber attack in mind.

Watch...


In the early part of my software career, i worked on the Human Machine Interface (HMI) software of two different companies - Omron's NTWin and Mitsubishi's GOT.

As the Human Machine Interface or the HMI software used for SCADA were not written keeping cyber attacks on mind, they are just plain vulnerable to the hackers.

Within the various SCADA solutions, the HMI represents the clearest and most present target for attackers. The HMI acts as a centralised hub for managing critical infrastructure. If an attacker succeeds
in compromising the HMI, nearly anything can be done to the infrastructure itself, including causing physical damage to SCADA equipment. Even if attackers decide not to disrupt operations, they can still exploit the HMI to gather information about a system or disable alarms and notifications meant to alert operators of danger to SCADA equipment.

Read... Humans of Universe... Read...

Here is a document on the vulnerability of the HMI software.


From recent incidents in the USA - the vulnerability of HMI...

Oldsmar, Florida water treatment plant (2021): 

Attackers remotely accessed the HMI via insecure remote tools (e.g., TeamViewer with shared/default passwords) and tried to poison water by increasing sodium hydroxide levels.

Unitronics PLC/HMI hacks (2023 onward): 

IRGC-affiliated actors ("CyberAv3ngers") defaced HMI screens at U.S. water facilities and elsewhere by exploiting internet-exposed devices with default passwords ("1111"). please educate me on these two incidents 

And here we go - the sophisticated malware called Stuxnet - which was responsible for crippling the Iranian nuclear plant...

Can't believe?

Watch how it targeted the SIEMENS PLC at a nuclear plant in Iran.



Stuxnet was crafted to exploit specific vulnerabilities in Windows and the Siemens software stack. The worm utilized multiple zero-day exploits in Windows and targeted Siemens Step7 software running on Windows systems to reprogram PLCs. Since Stuxnet's payload and propagation mechanisms were tailored to this environment, a system running Linux would inherently be immune to these specific exploits.

You know that most legacy HMI software was written using C++, and memory corruption is one of the most common vulnerabilities in HMI software.



I, therefore, was just wondering about the suitability of usage of Rust instead of C++ for writing Human Machine Interface software as the former is designed to handle the memory corruption issue quite nicely.

And voila - my guess was correct...

Rust can be a compelling alternative to C++ for developing SCADA Human-Machine Interfaces (HMIs), especially considering the memory safety advantages Rust offers. Here are some key points on why Rust could be a better choice:

Memory Safety

Elimination of Common Vulnerabilities: 

Rust's design inherently prevents common memory-related issues such as buffer overflows, null pointer dereferencing, and use-after-free errors. These types of vulnerabilities are prevalent in systems programmed in C++.

Borrow Checker: 

Rust’s borrow checker enforces strict ownership and borrowing rules at compile-time, ensuring that memory safety issues are caught early in the development process, thereby reducing the risk of memory corruption in deployed systems.

Performance

Comparable to C++: Rust is designed to offer performance comparable to C and C++. It achieves this through zero-cost abstractions, meaning you can write high-level code without incurring a performance penalty.

Efficient Concurrency: Rust's concurrency model prevents data races at compile time, allowing for safe and efficient concurrent programming, which is crucial for the high reliability and performance required in SCADA systems.

Modern Language Features

Error Handling: Rust provides robust error handling mechanisms through its Result and Option types, promoting safer and more explicit error management compared to exceptions in C++.
Strong Type System: Rust’s strong and expressive type system helps catch more errors at compile time, reducing runtime bugs and improving overall code quality.

Ecosystem and Tooling

Growing Ecosystem: Rust’s ecosystem is rapidly growing, with many libraries and tools available for systems programming, networking, and interfacing with hardware, which are essential for SCADA systems.

Cargo: Rust’s package manager and build system, Cargo, simplifies dependency management, builds, and project organization, contributing to developer productivity and code maintainability.

Adoption and Community

Industry Adoption: While Rust is still relatively new compared to C++, it has been gaining traction in various industries, including embedded systems and safety-critical applications, demonstrating its suitability for high-reliability domains like SCADA.

Active Community: Rust has a vibrant and supportive community, which helps in quickly resolving issues, sharing best practices, and continuously improving the language and its ecosystem.

Challenges

Learning Curve: The main challenge in adopting Rust is its steep learning curve, especially for developers accustomed to C++. The concepts of ownership, borrowing, and lifetimes can take time to master.


In summary, Rust offers significant advantages in terms of memory safety, performance, and modern language features, making it a strong candidate for developing SCADA HMIs. Its ability to prevent common vulnerabilities associated with memory corruption makes it particularly appealing for the high-security requirements of SCADA systems.

And now as CrowdStrike hitting hard, the C++ memory exception is already in news.

Is null pointer exception the reason for CrowdStrike? see below...


Shall we move from C++ to Rust?

Tuesday, April 9, 2024

Observer pattern in Rust - driven by intrinsic motivation...


Work is worship...

 The observer design pattern is a very popular design pattern in the Object Oriented world. I must admit, I first saw the usefulness of this design pattern while studying the document view architecture of the MFC source code.

Later on, I used this pattern in many places.

There is a lot of similarity between the Observer Pattern, the Callback mechanism, and the Event Handler pattern in Java. Usually, the callback method is used when there is only one observer who awaits the signal from the subject.

So, let me put it in this fashion.

Suppose, there is a central document that is viewed by a few applications - someone is viewing it in a spreadsheet, someone as a Pie chart, and so on.

Now if the data in the document is updated, all the viewers must be updated and they should synchronise their views with the latest data set. So basically all the viewers were observing the central data. The moment it changes, all the observers get their respective views updated.

The class diagram and the sequence diagram of the observer pattern will be as follows.


Class Diagram




Sequence Diagram

Here goes an example of Observer Pattern written in Rust.


trait Observer {

fn update(&self,data:&str);

}


struct Subject<'a> {

observers: Vec<&'a dyn Observer>,

state: String,

}


impl<'a> Subject<'a> {

fn new(state: String) -> Self {

Self {

observers: Vec::new(),

state: state,

}

}


fn attach(&mut self, observer: &'a dyn Observer) {

self.observers.push(observer);

}


fn detach(&mut self, observer: &dyn Observer) {

self.observers.retain(|o| !std::ptr::eq(*o, observer));

}


fn notify(&self) {

for o in &self.observers {

o.update(&self.state);

}

}


fn set_state(&mut self, state: String) {

self.state = state;

self.notify();

}

}


struct ConcreteObserver {

name: String,

}




impl Observer for ConcreteObserver {

fn update(&self,data:&str) {

println!("{} received data: {}",self.name,data);

}

}



fn main() {

let mut subject = Subject::new("initial data".to_string());


let observer1=ConcreteObserver {

name: "Observer 1".to_string(),

};


let observer2=ConcreteObserver {

name: "Observer 2".to_string(),

};



subject.attach(&observer1);

subject.attach(&observer2);



subject.set_state("updated_data".to_string());


subject.detach(&observer2);


subject.set_state("Again updated data".to_string());


subject.detach(&observer1);

}


Explanation of Key Concepts:

Lifetimes ('a):

The lifetime 'a ties the lifetimes of the observers

to the lifetime of the Subject. This ensures that all observer

references in the vector remain valid as long as the Subject

exists.



Trait Objects (dyn Observer):

The dyn Observer in the Vec<&'a dyn Observer> denotes a trait

object. A trait object allows different types that implement

the Observer trait to be stored in the same collection (Vec).

This enables polymorphism, where the exact type of the observer

is determined at runtime.


Important Considerations

Lifetime Management:

Ensure that the lifetimes of all observers are correctly managed

to avoid dangling references.

Trait Object Overhead:

Using trait objects (dyn Trait) introduces some runtime overhead

due to dynamic dispatch.


&mut self:


  • &mut self in a method signature allows the method to modify the state of the object it's called on.
  • It’s part of Rust's strict ownership and borrowing rules, ensuring safe and concurrent access to data.
  • You must declare the instance as mutable (mut) to call such a method
  • Friday, March 29, 2024

    Adapter pattern in Rust - my exploration continues - in Rust, I keep my Trust...

     

    It's truly said that if you teach a person, actually two people learn.

    As a guru of my young son, Ridit, I taught him many design patterns and he implemented them in three different languages.

    Here's his discussion on Adaptor Design Pattern.

    Please go through his explanation.




    Today I implemented his work of Adapter Pattern using Rust.

    In Rust... I keep my Trust.

    Rust addresses memory safety and concurrency issues that plague other systems languages like C and C++. This makes it attractive for building reliable, high-performance systems.

    Rust is already being used in embedded systems, operating system kernels, and high-performance computing. Rust's memory safety makes it ideal for applications where security is paramount.

    In simple words, the future of Rust programming language looks bright.

    Here's the source code for the Adapter Design Pattern in Rust.

    use std::io;


    trait IWeatherFinder {

    fn get_temperature(&self, city_name : &str)-> i32;

    }


    struct WeatherFinder{}

    impl IWeatherFinder for WeatherFinder{

    fn get_temperature(&self, city_name : &str) -> i32{

    if (city_name.trim().eq("Kolkata".trim())){

    40

    }

    else{

    println!("Unknown City Name...Could not read temperature");

    -273

    }

    }

    }


    trait iWeatherFinderClient {

    fn get_temperature (&self, city_pincode : i32)->i32;

    }


    struct WeatherAdapter{}

    impl WeatherAdapter {

    fn get_city_name (&self, pincode : i32) -> &str {

    if pincode == 700078 {

    "Kolkata".trim()

    }

    else {

    "UnknownCity"

    }

    }

    fn get_temperature (&self, pincode : i32)-> i32 {

    let city_name = self.get_city_name(pincode);

    let weatherfinder : WeatherFinder = *Box::new(WeatherFinder{});

    weatherfinder.get_temperature(city_name)

    }

    }


    fn main() {

    println!("Enter pin code");

    let mut pincode = String::new();

    io::stdin().read_line(&mut pincode).expect("Failed to read line");

    let pin_code: i32 = pincode.trim().parse().expect("Input not an integer");

    let weatheradapter = WeatherAdapter{};

    let temperature: i32 = weatheradapter.get_temperature(pin_code);

    println!("The temparature is {} degree celcius", temperature);

    }


    Output:

    Enter pin code

    700078

    The temperature is 40 degree celcius

    Thursday, March 28, 2024

    Strategy Design Pattern in Rust...


    Karmyog - Work is worship...

    In Rust, i keep my Trust...

    The strategy design pattern is a behavioral design pattern that lets you dynamically switch the behavior of an object at runtime. It achieves this by separating the core functionality of the object from the specific algorithms it uses.

    Here's a breakdown of the core concepts:

    Strategy Interface: This interface defines the common operation that all the different algorithms will implement. This ensures that all the interchangeable strategies can be used by the context object.

    Concrete Strategies: These are the classes that implement the specific algorithms. Each concrete strategy class implements the strategy interface and provides its own unique behavior for the operation.

    Context Object: This object holds a reference to a strategy object and delegates the specific operation to it. It can change its behavior at runtime by switching the reference to a different concrete strategy.

    Here's an example of an UML diagram for the Strategy Design Pattern.



    In my code, the 

    trait TransportationToAirport{

    fn going_to_the_airport(&self);

    }

    plays the role of the Strategy interface.

    Three concrete Strategy classes have been derived from this interface  - namely, By_Ola, By_Bus and By_Rapido.

    These concrete strategy classes help to pick up a specific way for going to the airport dynamically, i.e.,  in runtime.

    Here's the source code for Strategy Pattern implemented in Rust.

    use std::io;


    trait TransportationToAirport{

    fn going_to_the_airport(&self);

    }


    struct By_Bus{}


    impl TransportationToAirport for By_Bus {

    fn going_to_the_airport(&self) {

    println!("Going to airport by Bus...");

    }

    }


    struct By_Ola{}



    impl TransportationToAirport for By_Ola{

    fn going_to_the_airport(&self) {

    println!("Going to airport by Ola...")

    }

    }


    struct By_Rapido{}


    impl TransportationToAirport for By_Rapido{

    fn going_to_the_airport(&self) {

    println!("Going to airport by Rapido...");

    }

    }



    struct Traveller{

    strategy : Box<dyn TransportationToAirport>,

    }


    impl Traveller{

    fn new(strategy: Box<dyn TransportationToAirport>) -> Self {

    Traveller { strategy }

    }

    fn travel(&self){

    self.strategy.going_to_the_airport();

    }

    pub fn set_strategy(&mut self, strategy: Box<dyn TransportationToAirport>) {

    self.strategy = strategy;

    }

    }



    fn main() {

    println!("Enter your choice...");

    let mut choice = String::new();

    io::stdin().read_line(&mut choice);

    if choice.trim().eq("BUS".trim()){

    let traveller : Traveller = Traveller::new(Box::new(By_Bus{}));

    traveller.travel();

    }

    if choice.trim().eq("OLA".trim()){

    let traveller : Traveller = Traveller::new(Box::new(By_Ola{}));

    traveller.travel();

    }

    if choice.trim().eq("RAPIDO".trim()){

    let traveller : Traveller = Traveller::new(Box::new(By_Rapido{}));

    traveller.travel();

    }

    }

    Here's the output of the above code:

    Enter your choice...

    OLA

    Going to airport by Ola...