How the value 2 came,pls explain

The Gateway to Computer Science Excellence

+37 votes

The following two functions $P1$ and $P2$ that share a variable $B$ with an initial value of $2$ execute concurrently.

$$\begin{array}{|l|l|}\hline \text{} & \text{} \\ \text{P1() \{ } & \text{P2()\{} \\ \text{ C = B - 1;} & \text{ D = 2 * B; } \\ \text{ B = 2 * C;} & \text{ B = D - 1;} \\ \text{\}} & \text{\}}\\ \\\hline \end{array}$$

The number of distinct values that $B$ can possibly take after the execution is______________________.

$$\begin{array}{|l|l|}\hline \text{} & \text{} \\ \text{P1() \{ } & \text{P2()\{} \\ \text{ C = B - 1;} & \text{ D = 2 * B; } \\ \text{ B = 2 * C;} & \text{ B = D - 1;} \\ \text{\}} & \text{\}}\\ \\\hline \end{array}$$

The number of distinct values that $B$ can possibly take after the execution is______________________.

+37 votes

+6

execute P1 -

C = B - 1;

now c =1

let suppose now P2 executing because of concurrent process-

P2(){ D = 2 * B; B = D - 1; }

now B= 3

after this P1 executes second instruction-

B = 2 * C;

which is B= 2*1=2

+2

We should also add the case where P2-P1-P2 . Yes the final value comes out to be B = 3 , which is already present , but still 4 cases to check in total right ?

0

is it a hit and trial process to find out the number of distinct values .Is there is no sure shot way which can be applied to n processes?

+33 votes

Let P1(){ A, B } and P2(){ 1, 2 }

Now possible sequence and value of variables B, C and D are as follow -->

- A B 1 2 {3,1,4}
- A 1 B 2 {3,1,4}
- A 1 2 B {2,1,4}
- 1 A B 2 {3,1,4}
- 1 A 2 B {2,1,4}
- 1 2 A B {4,2,4}

So Number of distinct values that B can possibly take after the execution is 3 {2,3,4}.

PS: Little bit long but error free method.

+5

If number of combinations are less like 6,then we can solve like this as there is 100% surety of getting correct answer.

+1

Why did we consider these Operations as atomic. Whereas, I've done some questions where we break one instruction into 3 parts (read, operate, execute). For example -

Initially, X=0.

P1(){

X++;

X++;

}

P2{

X++;

X++;

}

Minimum value of X after both functions get executed is 2 (possible only if we break X++ as

1. Read(X)

2. X++

3. Write(X) )

Initially, X=0.

P1(){

X++;

X++;

}

P2{

X++;

X++;

}

Minimum value of X after both functions get executed is 2 (possible only if we break X++ as

1. Read(X)

2. X++

3. Write(X) )

+4 votes

**P1-P2: B = 3
P2-P1: B = 4
P1-P2-P1: B = 2
P2-P1-P2: B = 3**

**Total distinct values {2,3,4}.**

- All categories
- General Aptitude 1.9k
- Engineering Mathematics 7.5k
- Digital Logic 2.9k
- Programming and DS 4.9k
- Algorithms 4.4k
- Theory of Computation 6.2k
- Compiler Design 2.1k
- Databases 4.1k
- CO and Architecture 3.4k
- Computer Networks 4.2k
- Non GATE 1.4k
- Others 1.4k
- Admissions 595
- Exam Queries 573
- Tier 1 Placement Questions 23
- Job Queries 72
- Projects 18

50,737 questions

57,292 answers

198,231 comments

104,914 users