Friday, July 3, 2026

Bridge Pattern using Python...

Bridge Pattern is a structural design pattern that decouples an abstraction from its implementation, allowing both to evolve independently.

Why it exists (The Problem)When you have classes that can vary in two or more independent dimensions, simple inheritance leads to a combinatorial explosion of subclasses.
Example:
  • You have shapes: Circle, Square
  • You have rendering APIs: OpenGL, DirectX, Vulkan
Using inheritance, you end up with: CircleOpenGL, CircleDirectX, SquareOpenGL, etc. — and it gets worse as you add more shapes or renderers.Solution: Bridge PatternThe pattern splits the class into two hierarchies:
  1. Abstraction – High-level control logic (e.g., Shape)
  2. Implementation – Low-level platform-specific details (e.g., Renderer)
These two hierarchies are connected via a bridge (composition instead of inheritance).
Here is a Python implementation of the Bridge Pattern.



from
abc import ABC, abstractmethod

# ==================== Implementor 1: Color ====================
class Color(ABC):
@abstractmethod
def get_color(self) -> str:
pass

@abstractmethod
def paint(self):
pass


class Red(Color):
def get_color(self) -> str:
return "Red"

def paint(self):
print("Painting the vehicle in vibrant Red...")


class Black(Color):
def get_color(self) -> str:
return "Black"

def paint(self):
print("Painting the vehicle in deep Black...")


# ==================== Implementor 2: Gear ====================
class Gear(ABC):
@abstractmethod
def get_type(self) -> str:
pass

@abstractmethod
def shift(self):
pass


class ManualGear(Gear):
def get_type(self) -> str:
return "Manual"

def shift(self):
print("Shifting gears manually...")


class AutoGear(Gear):
def get_type(self) -> str:
return "Automatic"

def shift(self):
print("Shifting gears automatically...")


# ==================== Abstraction: Vehicle ====================
class Vehicle(ABC):
def __init__(self, color: Color, gear: Gear):
self.color = color # Bridge to Color implementor
self.gear = gear # Bridge to Gear implementor

@abstractmethod
def display(self):
pass

def paint_vehicle(self):
self.color.paint()

def change_gear(self):
self.gear.shift()


# ==================== Refined Abstractions ====================
class SmallCar(Vehicle):
def display(self):
print(f"=== Small Car ===")
print(f"Color: {self.color.get_color()}")
print(f"Gear: {self.gear.get_type()}")
self.paint_vehicle()
self.change_gear()
print("Driving smoothly in the city...\n")


class Truck(Vehicle):
def display(self):
print(f"=== Truck ===")
print(f"Color: {self.color.get_color()}")
print(f"Gear: {self.gear.get_type()}")
self.paint_vehicle()
self.change_gear()
print("Hauling heavy load on the highway...\n")


# ==================== Client Code ====================
if __name__ == "__main__":
# Create implementors
red = Red()
black = Black()
auto = AutoGear()
manual = ManualGear()

# Create vehicles with different combinations (independent variation)
print("Creating vehicles using Bridge Pattern:\n")

car1 = SmallCar(red, auto)
car1.display()

car2 = Truck(black, manual)
car2.display()

car3 = SmallCar(black, auto)
car3.display()

Here's what the above solution would look like without the Bridge Pattern - look at the image below.

Look at the left-side hierarchy of classes. With more and more attributes, the inheritance tree would have exploded.

So... comes the Bridge Pattern - a nice solution without so many classes as depicted in the right hierarchy of classes.





I hope I have clarified the Bridge Pattern clearly.

Enjoy...

Tuesday, June 9, 2026

The creator of FFmpeg and many more - the French scientist, Fabrice Bellard, and why it's all about intrinsic motivation...

When people talk about "10x engineers," one name that often comes up is Fabrice Bellard.

He created:

  • FFmpeg — the multimedia engine behind countless video platforms and applications.
  • QEMU — a foundational technology for virtualization and operating system development.
  • Tiny C Compiler.
  • QuickJS.
  • TinyGL, JSLinux, advanced compression systems, and even world-record π calculations.
Here's a condensed timeline of major projects by Fabrice Bellard and how his interests evolved over time:
YearProjectSignificance
1997            Tiny C CompilerExtremely small and fast C compiler; demonstrated Bellard's obsession with efficiency.

2000               FFmpegCreated one of the most influential multimedia frameworks ever built.

2003                QEMURevolutionary CPU emulator capable of dynamic binary translation.
2004                TinyGL
Compact software rendering implementation of OpenGL.

2005        Binary Translation research             advancesContinued improving QEMU's performance and architecture.

2009        Pi Computation RecordComputed trillions of digits of π on a personal computer, setting records.

2011        BPG groundworkBegan exploring next-generation image compression technologies.

2015        BPGImage format offering better compression than JPEG.

2017    JSLinux improvementsEntire Linux system running inside a web browser.

2019    QuickJSSmall, standards-compliant JavaScript engine written from scratch.

2021+    Compression, networking,     emulation researchContinued independent experimentation and publication of new ideas.

What is remarkable is not merely the number of projects, but their influence. FFmpeg became part of the infrastructure of modern video processing, while QEMU became a cornerstone of virtualization and emulation.



Why this points to intrinsic motivation

Bellard's career illustrates a pattern seen in many exceptional creators:

  1. They work on problems because they find them fascinating. Bellard has repeatedly tackled difficult technical challenges—from compiler design to CPU emulation to compression algorithms. One description of his approach quotes him as enjoying problems others consider impossible.

  2. The projects often start before there is an obvious market. FFmpeg began in 2000 as an open-source multimedia project. QEMU started as a personal effort. These were not obvious startup opportunities at the time.

  3. Mastery becomes its own reward. Many of Bellard's projects seem driven by a desire to see how far efficiency, simplicity, and elegant engineering can be pushed.

A broader lesson

If we study people like Fabrice Bellard, Linus Torvalds, or Donald Knuth, a common thread emerges:

They were not primarily motivated by status, followers, or even money.

They were obsessed with understanding systems deeply and building things that did not yet exist.

Money and recognition often arrived later as side effects.

We must remember that the most significant breakthroughs often come from years of curiosity-driven exploration rather than from chasing immediate rewards.

In that sense, FFmpeg is not just a software project. It is evidence that sustained intrinsic motivation can produce tools that end up supporting an entire industry.

Saturday, May 23, 2026

Class level locking in C++ - serializing multiple threads...


When I studied Android AsyncTask, especially

when Serialexecutor was the norm, I found how

Google engineers have designed to serialize

execution of multiple threads. My original

code simulating similar effects using Java

was done more than a decade ago. Here it is.


Today I did the same effect, but this time with modern C++.


Here we go.


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

// Name : ClassLevelLockingThreadSerialization.cpp

// Author : Som

// Version :

// Copyright : som-itsolutions

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

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


#include <iostream>

#include <future>

#include <chrono>

#include <mutex>


class ExampleClass {

private:

static std::mutex classMutex;


public:


static void testMethod(const std::string& threadName) {


std::lock_guard<std::mutex> lock(classMutex);


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


std::cout

<< "The testMethod for "

<< threadName

<< std::endl;


std::this_thread::sleep_for(

std::chrono::seconds(1)

);

}

}

};


std::mutex ExampleClass::classMutex;


int main() {


auto f1 = std::async(

std::launch::async,

ExampleClass::testMethod,

"Thread 1"

);


auto f2 = std::async(

std::launch::async,

ExampleClass::testMethod,

"Thread 2"

);


f1.get();

f2.get();

}


Explanation


Understanding the Synchronization

The important part of the program is:

std::lock_guard<std::mutex> lock(classMutex);

This line acquires the mutex before entering the critical section. Since the mutex is declared as static, it is shared across all threads and all invocations of the method.

As a result:

  • only one thread can execute testMethod() at a time
  • the second thread waits until the first thread releases the mutex
  • thread execution becomes serialized

This is conceptually similar to Java’s static synchronized methods.

Why Use std::lock_guard?

Modern C++ prefers RAII-based locking instead of manually calling:

mutex.lock();
mutex.unlock();

std::lock_guard automatically releases the mutex when the object goes out of scope, making the code safer and exception-resistant.

Why Use std::async?

Instead of manually creating and managing std::thread objects, std::async provides a higher-level abstraction for asynchronous task execution.

Benefits include:

  • automatic thread management
  • future-based synchronization
  • cleaner code
  • safer resource handling

Final Thoughts

Modern C++ concurrency has evolved significantly from traditional thread programming. Features such as futures, mutexes, async execution, coroutines, and task systems enable developers to write safer and more scalable concurrent applications.

This small example demonstrates a foundational concept that appears everywhere in modern systems programming:

  • game engines
  • rendering systems
  • simulation frameworks
  • CAD software
  • scientific computing systems

Understanding synchronization primitives like mutexes is an important first step toward mastering advanced concurrent architectures in modern C++.