25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

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.

Solutions to Chapter 18 | Threads and 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() and 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() and release()<br />

methods How could you make your implementation thread safe and 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 and 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 />

2 5 9<br />

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

pg 86

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

Saved successfully!

Ooh no, something went wrong!