Wednesday, 3 August 2016

Mutex vs Semaphore

What are the differences between Mutex vs Semaphore? When to use mutex and when to use semaphore?
Concrete understanding of Operating System concepts is required to design/develop smart applications. Our objective is to educate  the reader on these concepts and learn from other expert geeks.
As per operating system terminology, mutex and semaphore are kernel resources that provide synchronization services (also called as synchronization primitives). Why do we need such synchronization primitives? Won’t be only one sufficient? To answer these questions, we need to understand few keywords. Please read the posts onatomicity and critical section. We will illustrate with examples to understand these concepts well, rather than following usual OS textual description.
The producer-consumer problem:
Note that the content is generalized explanation. Practical details vary with implementation.
Consider the standard producer-consumer problem. Assume, we have a buffer of 4096 byte length. A producer thread collects the data and writes it to the buffer. A consumer thread processes the collected data from the buffer. Objective is, both the threads should not run at the same time.
Using Mutex:
A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa.
At any point of time, only one thread can work with the entire buffer. The concept can be generalized using semaphore.
Using Semaphore:
A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.
Misconception:
There is an ambiguity between binary semaphore and mutex. We might have come across that a mutex is binary semaphore. But they are not! The purpose of mutex and semaphore are different. May be, due to similarity in their implementation a mutex would be referred as binary semaphore.
Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there is ownership associated with mutex, and only the owner can release the lock (mutex).
Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend calls you, an interrupt is triggered upon which an interrupt service routine (ISR) signals the call processing task to wakeup.
General Questions:
1. Can a thread acquire more than one lock (Mutex)?
Yes, it is possible that a thread is in need of more than one resource, hence the locks. If any lock is not available the thread will wait (block) on the lock.
2. Can a mutex be locked more than once?
A mutex is a lock. Only one state (locked/unlocked) is associated with it. However, a recursive mutex can be locked more than once (POSIX complaint systems), in which a count is associated with it, yet retains only one state (locked/unlocked). The programmer must unlock the mutex as many number times as it was locked.
3. What happens if a non-recursive mutex is locked more than once.
Deadlock. If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. It is because no other thread can unlock the mutex. An operating system implementer can exercise care in identifying the owner of mutex and return if it is already locked by same thread to prevent deadlocks.
4. Are binary semaphore and mutex same?
No. We suggest to treat them separately, as it is explained signalling vs locking mechanisms. But a binary semaphore may experience the same critical issues (e.g. priority inversion) associated with mutex. We will cover these in later article.
A programmer can prefer mutex rather than creating a semaphore with count 1.
5. What is a mutex and critical section?
Some operating systems use the same word critical section in the API. Usually a mutex is costly operation due to protection protocols associated with it. At last, the objective of mutex is atomic access. There are other ways to achieve atomic access like disabling interrupts which can be much faster but ruins responsiveness. The alternate API makes use of disabling interrupts.
6. What are events?
The semantics of mutex, semaphore, event, critical section, etc… are same. All are synchronization primitives. Based on their cost in using them they are different. We should consult the OS documentation for exact details.
7. Can we acquire mutex/semaphore in an Interrupt Service Routine?
An ISR will run asynchronously in the context of current running thread. It is not recommended to query (blocking call) the availability of synchronization primitives in an ISR. The ISR are meant be short, the call to mutex/semaphore may block the current running thread. However, an ISR can signal a semaphore or unlock a mutex.
8. What we mean by “thread blocking on mutex/semaphore” when they are not available?
Every synchronization primitive has a waiting list associated with it. When the resource is not available, the requesting thread will be moved from the running list of processor to the waiting list of the synchronization primitive. When the resource is available, the higher priority thread on the waiting list gets the resource (more precisely, it depends on the scheduling policies).
9. Is it necessary that a thread must block always when resource is not available?
Not necessary. If the design is sure ‘what has to be done when resource is not available‘, the thread can take up that work (a different code branch). To support application requirements the OS provides non-blocking API.
For example POSIX pthread_mutex_trylock() API. When mutex is not available the function returns immediately whereas the API pthread_mutex_lock() blocks the thread till resource is available.
TCS aptitude 2013
Note: if anyone need answers comment below
1. If the price of an item is decreased by 10% and then increased by 10%, the net effect on the price of the item is
A. A decrease of 99%
B. No change
C. A decrease of 1%
D. An increase of 1%

2. If m is an odd integer and n an even integer, which of the following is definitely odd?
A. (2m+n)(m-n)
B. (m + n2) + (m - n2)
C. m2 + mn + n2
D. m +n

3. What is the sum of all even integers between 99 and 301?
A. 40000
B. 20000
C. 40400
D. 20200

4. There are 20 balls which are red, blue or green. If 7 balls are green and the sum of red balls and green balls is
less than 13, at most how many red balls are there?
A. 4
B. 5
C. 6
D. 7

5. If n is the sum of two consecutive odd integers and less than 100, what is greatest possibility of n?
A. 98
B. 94
C. 96
D. 99

6. x2 < 1/100, and x < 0 what is the highest range in which x can lie?
A. -1/10 < x < 0
B. -1 < x < 0
C. -1/10 < x < 1/10
D. -1/10 < x

7. There are 4 boxes colored red, yellow, green and blue. If 2 boxes are selected, how many combinations are
there for at least one green box or one red box to be selected?
A. 1
B. 6
C. 9
D. 5

8. All faces of a cube with an eight - meter edge are painted red. If the cube is cut into smaller cubes with a two -
meter edge, how many of the two meter cubes have paint on exactly one face?
A. 24
B. 36
C. 60
D. 48

9. Two cyclists begin training on an oval racecourse at the same time. The professional cyclist completes each lap
in 4 minutes; the novice takes 6 minutes to complete each lap. How many minutes after the start will both cyclists
pass at exactly the same spot where they began to cycle?
A. 10
B. 8
C. 14
D. 12

10. M, N, O and P are all different individuals; M is the daughter of N; N is the son of O; O is the father of P; Among
the following statements, which one is true?
A. M is the daughter of P
B. If B is the daughter of N, then M and B are sisters
C. If C is the granddaughter of O, then C and M are sisters
D. P and N are bothers

Sunday, 26 June 2016

How to crack a job interview



10 Tips to Crack Job Interview



Sleepless Nights, Loss of Appetite, Anxiety etc….Don’t take me wrong as I am not discussing about some disease but these are the few symptoms of Job Interview Fear or Phobia. Nothing to worry about the same, these are very common and during research it was observed that approx 80% of candidates suffer from Interview Fear / Phobia…At the same time those who overcome the fear of interview, have very high probability of being successful…There are some tips and tricks which can help u in getting your dream job…Lets find out how to overcome fear of interview & some useful Tips to Crack Job Interview.

1. Overcome the Fear of Rejection / Losing: Firstly lets understand why we fear the interview, answer is very simple..its not fear of interview but fear of rejection so it is very important to overcome the fear of rejection…How can we overcome the fear of rejection?
It is very easy to handle this fear, by simply changing your attitude and approach towards interview…Self confidence is very important in regard…I am going to share success mantra“Always appear in Interview with attitude as in you don’t need this job” YES, you read it right…Always appear in interview with this attitude…This approach will boost your Self Confidence. As per some psychological researches, if we need some thing in life then we chase it..When we chase, we fear loosing it even before getting it..1st focus should be to achieve that particular objective, once u achieve then only fear of losing comes into picture…So appear in interview with Full Confidence and with an Attitude that you don’t need this job…It will help you to overcome the fear of rejection or losing the job. No company will hire fearful person so overcome your fear if want the Job.
2.  Understand Job Requirement: It is very important to understand what is job profile and whether u fit in this profile or not…Always ask for Job Description before appearing for interview…Identify your strengths & be clear on what kind of candidate organization is looking for..It will help you to decide your approach during course of interview.
3. What all you are bringing it to the table? Always think that if u need this particular job then at the same time, organization is also looking for good candidate…During interview always focus on what all skill sets you will bring to organization & how it will benefit the organization in long benefit…Job is also doing a business, in our daily life if we buy any product or hire any service..we always look how this product or service will benefit us similarly you are also doing business with organization and try to showcase how organization is going to benefit if they offer this job to u.
4. Probable Questions & Answers: Once you are clear on Job Requirement, make a list of probable questions and their answers i.e. what all an interviewer can ask you..If need arises take help of your friends who are in similar position or industry…Trust me if u do this exercise seriously, you will be able to find out atleast 80% of questions which can be asked during the interview.
5 Never Fudge or fabricate your CV: Its a biggest and most common mistake by most of candidates..My sincere advice never ever fudge your CV…Organizations are smart & they will find out very easily that you have fabricated your CV. It can create problem for u in future and can even spoil your career, so always be honest in your approach.
6. Never Argue with Interviewer: It is advisable not to enter into any kind of  argument with Interviewer during interview..Lets accept that the person who is taking the interview has more experience, just listen & don’t argue to justify your point..I am not saying don’t put across your point but put it in a positive manner & don’t argue to justify that your are correct.
7. Be Honest & Flexible: Always be honest during interview..If u don’t know any answer just accept the same rather trying to give wrong answers…Besides knowledge, organizations give lot of importance to people who are honest in approach and also flexible in their approach…Never be rigid in your approach as business environment is changing very fast these days…Organizations always give importance to ppl with flexible approach rather rigid in nature.
8. Ask for feedback at the end of Interview: Before the interview closes, ask for feedback from interviewer irrespective how your interview went..It gives very positive impression about candidate…Organization feel that candidate has positive attitude & is willing to accept feedback
9. Salary Negotiations: Never ever ask for unrealistic salary hikes as it gives impression that you are not serious about the job and just changing the job for money….Kindly do your homework before salary negotiation i.e. with your experience and for the particular job profile what is industry benchmark…For junior and middle management, normal salary hike is in the range of 25% to 40%…Also in some of critical job profiles like treasury in banking you might get very high salary hike.
10. Never ditch the organization after accepting the Job: Again very common mistake and some ppl have habit of keep trying in various organizations for better package after receiving job offer & if they get another job, they simply say NO before joining..Trust me it can spoil your career in long run and you will never be able to reach top management with this attitude…World is very small and in this networked age you can’t hide these kind of actions…In future you will again come across same people & then no one will hire, if they find that you indulged in these tactics..If u don’t wish to join then pls don’t accept offer letter but after accepting if u say NO then it is totally unethical and unprofessional.
I have tried to cover all critical points but if i missed any, you are most welcome to add by commenting below..Also you can share you views/opinions on this article through comment section.

Welcome to the Planet of Engineers

welcome to the world of engineers brought to you by Mohammed Mohiddin
this is my first post