Posts

Showing posts from 2015

Object oriented programming (Introduction) - Article 1

Hi Folks, Let's start off on OOP and C++. This is an introductory article for the bigger things coming in the future weeks. What is OOP or Object oriented programming? OOP stands for object oriented programming. C#, C++ and Java are examples of object oriented languages, where as C, Pascal are examples of procedural languages. Modularity, extensibility, reusability and maintainability are some of the advantages of OO languages. In OOP, the software programs are organized as OBJECTs. All the entities in OOP are modelled as objects. Suppose a problem is given, in procedural langauge like C, the problem is divided into functions (actions on data) and data are declared, whereas in C++, the problem is modelled as objects. For example, a problem on car in C will look like, float brake; float acceleration; main() {     accelerate_the_car();         if(obstacle == true)             apply_brake(); } void accelerate_the_car() { } void appl

Synchronization primitives: Mutex and Semaphore (Differences between Mutex and Semaphore) - Article 12

Hi Folks, Sorry, had to take a long break. In this article, let's summarize the differences between Mutex and Semaphore and this is the last article in the series. In the coming articles we shall discuss more about OO, Design, C++, etc and revisit synchronization as and when needed. Mutex Semaphore 1 Mutex is a locking mechanism only to ensure mutual exclusion, that is only one thread or process is allowed to execute the code in critical section. Semaphore can be used for locking, signalling and variety of problems as we have seen in the examples. 2 Mutex is owned and only thread that has locked the mutex can unlock it. Semaphore does not have ownership, anybody can unlock a semaphore. 3 Process wide. System wide. 4 Mutex is used to synchronize threads. Semaphore is used to synchronize threads/processes. 5 Simpler to use. Complex semantics. To

Synchronization primitives: Mutex and Semaphore (Condition Variables) - Article 11

Hi Folks, In previous articles, we have understood the synchronization constructs Mutex and Semaphore. Semaphore is a superior construct compared to a Mutex. Mutex is just a lock where as Semaphore can be used to solve variety of problems. I have explained Mutex & Semaphore using pseudo code and in recent articles, I have provided real PThreads & Mutex code which can be executed & tested in Linux. Going forward, we shall explore Condition Variables & the differences between Mutex & Semaphore. We shall also write some real Semaphore code in Linux. We shall also solve few more synchronization problems & conclude Mutex & Semaphore. In this article, let's explore the concept of Condition Variable. -> Mutex is just a locking mechanism. -> Semaphore can be used as a lock or as a signalling mechanism. Now, how can we use Mutex to solve serialization problems? That's where Condition Variables come into the picture. When we use the combinati

Synchronization primitives: Mutex and Semaphore (Sample Program) - Article 10

Hi Folks, I have run this program on Intel I5 processor running Ubuntu Linux. You can imagine the speed and this program is a very tiny one. But still the output is garbled. |3|The list is full Count: 3 ->|3|The list is full |1|The list is full ->|7||3||3|->->The list is full ->|1||2|The list is full ->->|3||1| ->The list is full The list is full The list is full |7|The list is full |7|The list is full The above is not expected output. You can see that list is not displayed properly. The synchronized version of program is shown below using Mutex variable by name pro(tection). #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<pthread.h> #include<stdio.h> #include<stdlib.h> typedef struct node {     struct node *link;     int data; } NODE; static int count = 0; NODE *head = NULL; pthread_mutex_t pro; NODE *get_node(void) {     int data = rand();     data = data % 13;     NODE *ptr = (NODE *)malloc(s

Synchronization primitives: Mutex and Semaphore (Sample Program) - Article 9

Hi Folks, In this article, I am going to present my version of producer consumer problem which we need to synchronize. The producer can produce a maximum of 5 elements and the consumer consumes 1 element at a time. All data is shared and hence, synchronization is needed. In this article, I am going to present the program. In the next article, we shall apply synchronization. #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<pthread.h> #include<stdio.h> #include<stdlib.h> typedef struct node {     struct node *link;     int data; } NODE; static int count = 0; NODE *head = NULL; NODE *get_node(void) {     int data = rand();     data = data % 13;     NODE *ptr = (NODE *)malloc(sizeof(NODE));     if(ptr != NULL) {         ptr->data = data;         ptr->link = NULL;     }     return ptr; } void print_node(NODE *ptr) {     printf("|%d|",ptr->data);     if(ptr->link != NULL) {  

Synchronization primitives: Mutex and Semaphore (Readers & Writers problem) - Article 8

Hi Friends, In this article, we shall solve the Readers & Writers problem. Readers & Writers problem: There may be m writers & n readers related to a shared data structure or a record in the database (some shared data). Only one writer thread can be updating the data, but there can be many readers accessing the data. The constraints are: 1. Any number of readers can be accessing the data in critical section. 2. Only one writer thread should be allowed to update the data in critical section. Solution: int readers = 0; // Shared variable to keep track of number of readers,                  // yes this also needs to be protected Semaphore readersProtect = 1; Semaphore roomEmpty = 1; Writers thread code: roomEmpty.wait();     // Update shared data, critical section for writers roomEmpty.signal(); Readers thread code: readersProtect.wait();     readers = readers + 1;     if(readers == 1)         roomEmpty.wait(); // First reader locks and bars wri

Synchronization primitives: Mutex and Semaphore (Rendezvous problem) - Article 7

In this article, we shall solve Rendezvous problem. Rendezvous problem: Imagine you and your friend plan to go to a trip and decide to meet in Railway station. None of you can proceed before the other has arrived. Once you have arrived, you inform (or signal) your friend via a message or a call then you wait for your friend. Your friend would also do the same thing if he came first. Similar real life solution can be applied to the threads Rendezvous problem. Thread 1: Event A1; Event B1; Thread 2: Event A2; Event B2; We have to ensure that T1 and T2 should proceed only after both A1 and A2 are complete. But, anybody can complete A1 or A2 first. Solution: Semaphore T1_Arrived = 0; Semaphore T2_Arrived = 0; Thread 1: Event A1; T1_Arrived.signal(); // Signal T1 has arrived T2_Arrived.wait(); // Wait for T2 Event B1; Thread 2: Event A2; T2_Arrived.signal(); // Signal T2 has arrived T1_Arrived.wait(); // Wait for T1 Event B2; Suppose T2 finishes A2, i

Synchronization primitives: Mutex and Semaphore (Serialization & Mutex problems using Semaphore) - Article 6

Hi Friends, In the previous articles, we have gained knowledge about Mutex and Semaphore. In this article, we shall see how a Semaphore can be used to solve serialization problem and Mutual Exclusion (Mutex) problem. Serialization problem: Thread 1: Event A; // Could be any code Thread 2: Event B; // Could be any code The problem is, we have to ensure that Event B or a particular code or instructions should always be executed after Event A or some other particular code. Basically, we are serializing the instructions irrespective of how the threads are scheduled to run. Solution: There are no resources here, we need to just signal, initialize Semaphore to 0. Semaphore SignalThread2 = 0; Thread 1: Event A; SignalThread2.signal(); Thread 2: SignalThread2.wait(); Event B; The code for Thread 1 and Thread 2 is as above. Irrespective of which thread is scheduled, Event A always occurs before Event B. How? Let's say Thread 2 is scheduled first, it executes

Synchronization primitives: Mutex and Semaphore (Explanation for Semaphore) - Article 5

Hi Folks, In the previous article, we saw what is Mutex or Mutual Exclusion. If critical section code is thought of as a single resource, only one thread will be allowed to use that resource. In this article, we shall see what is a semaphore and the solutions to few synchronization problems using the semaphore. A semaphore is very simple and easy to understand but it can solve complex synchronization problems. It is just a integer variable that can be initialized to any integer value (Usually non-negative: >= 0). After that, it is shared by the threads (Or processes). After initialization, only two operations can be performed on the semaphore: Decrement and Increment. The pseudo code of usage is as below: Semaphore MySem; MySem = 3; // Share MySem between n threads say 10 threads Thread 1: // Some code here MySem.Increment(); // MySem++ // Some more code here MySem.Decrement(); // MySem-- Thread 2: // Some code here MySem.Decrement(); // MySem -- // Some

Synchronization primitives: Mutex and Semaphore - Article 4

In this article, lets deep dive and understand the synchronization primitives - Mutex and Semaphore. Mutex or Mutual Exclusion is the basic form of synchronization primitive. Its a locking mechanism and ensures that only one thread or process can enter the critical section. After finishing the work (Like updating global variable or a data structure), the thread unlocks the mutex. NOTE: Mutex is used to synchronize threads. However, latest addition to POSIX standard says that the mutex can be used to synchronize processes if it's shared between them. A real world example follows: In olden days when there were no mobile phones, love birds (I mean lovers) used the STD phone booth extensively. What would they do? enter the phone booth, lock it and dial their partners home phone and start off on a long call - Outside, you could see a long line of people cursing the guy inside and waiting to get into the booth. i.e., one and only thread or process (Person) needs to enter critica

Synchronization problems in computers - Article 3

In this article, we will discuss a few synchronization problems in computers. In the next article, I will introduce Mutex and Semaphore and explain how they can be helpful in solving synchronization problems. 1. Dining philosophers problem This is a classical synchronization problem formulated by Edsger Dijkstra. Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers. (An alternative problem formulation uses rice and chopsticks instead of spaghetti and forks). Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when he has both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After he finishes eating, he needs to put down both forks so they become available to others. A philosopher can take the fork on his right or the one on his left as they be

Synchronization: Discussion about Mutex and Semaphore - Article 2

Let's do a double this week. I had mentioned about synchronization in computers but if I had discussed in previous article, it would be very big, hence I have split the previous article to discuss examples of synchronization in computers separately. In the previous article, I discussed about synchronization giving real world examples here: Synchronization article - 1 Let's see what synchronization is all about in the computers: The processor executes instructions serially one by one if it's a uniprocessor system. But synchronization involves things executing in parallel. Let's dig deep. 1. In uniprocessor systems, the OS takes care of scheduling different processes (Not covered in detail here) and makes multi tasking and multi processing possible. - The parallelism is pseudo and virtual to the humans because humans can't see and perceive the speed of processor's execution. - Even though instructions are executed serially, it appears to the users that e

Synchronization: Discussion about Mutex and Semaphore - Article 1

This is the first article in the series about Mutex and Semaphore. In my blog, I shall follow below sequence: 1. First, I will try to explain the concept. 2. Next, we shall see what problems the concept may solve or what problems may occur if the concept is not applied. 3. Finally, we shall see how the concept will solve the problem. In this article, I will try to cover what Synchronization in Computers is all about and different problems that can occur if Synchronization is not used. First we will see the real world examples and see what Synchronization is all about. Dictionary meaning is as below: 1. To cause to occur or operate with exact coincidence in time or rate. 2. Synchronization is the coordination of events to operate a system in unison. Let's try to understand in depth. Consider below examples: 1. Imagine soldiers doing march past in a parade. - They operate at the same time and everybody march in order. - They appear synchronized. How do they do it? - Every

A brief introduction to this blog

Hi everyone reading this blog, Before starting to publish articles, I would like to give brief introduction about "Why this blog?". When I explored Internet for knowledge about C++, OO Design, Design patterns, OS, Threads, Synchronization, etc, I found good articles, but I felt things were scattered and confusing at times. Example 1: Mutex Vs. Semaphore - Some claim that Binary semaphore is same as Mutex and some argue that they are not same. Example 2: Design patterns - Even with simple examples in many articles, difficult to grasp and think where to apply when a problem is given. With this, I got an idea as to why not me start a blog and stitch all the information from various books, articles and Internet sites together and create a blog to give in depth information about below topics and not restricted to: 1. C++ 2. STL 3. Design patterns 4. UML 5. OO Design 6. OS Concepts 7. Linux 8. Synchronization With the above introduction, I would like to start off with