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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

18.3 Implement a singleton design pattern as a template such that, for any given class<br />

Foo, you can call Singleton::instance() <strong>and</strong> get a pointer to an instance of a singleton<br />

of type Foo. Assume <strong>the</strong> existence of a class Lock which has acquire() <strong>and</strong> release()<br />

methods. How could you make your implementation thread safe <strong>and</strong> exception safe?<br />

SOLUTION<br />

1 using namespace std;<br />

2 /* Place holder for thread synchronization lock */<br />

3 class Lock {<br />

4 public:<br />

5 Lock() { /* placeholder code to create <strong>the</strong> lock */ }<br />

6 ~Lock() { /* placeholder code to deallocate <strong>the</strong> lock */ }<br />

7 void AcquireLock() { /* placeholder to acquire <strong>the</strong> lock */ }<br />

8 void ReleaseLock() { /* placeholder to release <strong>the</strong> lock */ }<br />

9 };<br />

10<br />

11 /* Singleton class with a method that creates a new instance of <strong>the</strong><br />

12 * class of <strong>the</strong> type of <strong>the</strong> passed in template if it does not<br />

13 * already exist. */<br />

14 template class Singleton {<br />

15 private:<br />

16 static Lock lock;<br />

17 static T* object;<br />

18 protected:<br />

19 Singleton() { };<br />

20 public:<br />

21 static T * instance();<br />

22 };<br />

23 Lock Singleton::lock;<br />

24<br />

25 T * Singleton::Instance() {<br />

26 /* if object is not initialized, acquire lock */<br />

27 if (object == 0) {<br />

28 lock.AcquireLock();<br />

29 /* If two threads simultaneously check <strong>and</strong> pass <strong>the</strong> first “if”<br />

30 * condition, <strong>the</strong>n only <strong>the</strong> one who acquired <strong>the</strong> lock first<br />

31 * should create <strong>the</strong> instance */<br />

32 if (object == 0) {<br />

33 object = new T;<br />

34 }<br />

35 lock.ReleaseLock();<br />

36 }<br />

37 return object;<br />

38 }<br />

pg 86<br />

2 5 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based

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

Saved successfully!

Ooh no, something went wrong!