27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 18 | Threads <strong>and</strong> Locks<br />

18.5 Suppose we have <strong>the</strong> following code:<br />

class Foo {<br />

public:<br />

A(.....); /* If A is called, a new thread will be created <strong>and</strong><br />

* <strong>the</strong> corresponding function will be executed. */<br />

B(.....); /* same as above */<br />

C(.....); /* same as above */<br />

}<br />

Foo f;<br />

f.A(.....);<br />

f.B(.....);<br />

f.C(.....);<br />

i) Can you design a mechanism to make sure that B is executed after A, <strong>and</strong> C is executed<br />

after B?<br />

iii) Suppose we have <strong>the</strong> following code to use class Foo. We do not know how <strong>the</strong><br />

threads will be scheduled in <strong>the</strong> OS.<br />

Foo f;<br />

f.A(.....); f.B(.....); f.C(.....);<br />

f.A(.....); f.B(.....); f.C(.....);<br />

Can you design a mechanism to make sure that all <strong>the</strong> methods will be executed in<br />

sequence?<br />

SOLUTION<br />

pg 86<br />

i) Can you design a mechanism to make sure that B is executed after A, <strong>and</strong> C is executed after B?<br />

1 Semaphore s_a(0);<br />

2 Semaphore s_b(0);<br />

3 A {<br />

4 /***/<br />

5 s_a.release(1);<br />

6 }<br />

7 B {<br />

8 s_a.acquire(1);<br />

9 /****/<br />

10 s_b.release(1);<br />

11 }<br />

12 C {<br />

13 s_b.acquire(1);<br />

14 /******/<br />

15 }<br />

ii) Can you design a mechanism to make sure that all <strong>the</strong> methods will be executed in sequence?<br />

1 Semaphore s_a(0);<br />

CareerCup.com<br />

2 6 2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!