Design a class which provides a lock if no deadlocks

Design a class which provides a lock only if there are no possible deadlocks.

Solution:
For our solution, we implement a wait / die deadlock prevention scheme.

	class MyThread extends Thread {
		long time;
		ArrayList<Resource> res = new ArrayList<Resource>();

		public ArrayList<Resource> getRes() {
			return res;
		}

		@Override
		public void run() {
			// Run infinitely
			time = System.currentTimeMillis();
			int count = 0;
			while (true) {
				if (count < 4) {
					if (Question.canAcquireResource(this, Question.r[count])) {
						res.add(Question.r[count]);
						count++;
						System.out.println("Resource: ["
								+ Question.r[count - 1].getId()
								+ "] acquired by thread: [" + this.getName()
								+ "]");
						try {
							sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				} else {
					this.stop();
				}
			}
		}

		public long getTime() {
			return time;
		}

		public void setRes(ArrayList<Resource> res) {
			this.res = res;
		}

		MyThread(String name) {
			super(name);
		}
	}

Thread safe and exception safe singleton design pattern

Implement a singleton design pattern as a template such that, for any given class Foo, you can call Singleton::instance() and get a pointer to an instance of a singleton of type Foo Assume the existence of a class Lock which has acquire() and release() methods How could you make your implementation thread safe and exception safe?

Solution:

using namespace std;
// Place holder for thread synchronization lock
class Lock {
public:
	Lock() { // placeholder code to create the lock
	} 
	~Lock() { // placeholder code to deallocate the lock
	} 
	void AcquireLock() { // placeholder to acquire the lock
	} 
	void ReleaseLock() { // placeholder to release the lock
	}
};

// Singleton class with a method that creates a new instance 
// of the * class of the type of the passed in template 
// if it does not already exist.
template <class T> class Singleton { 
private:
	static Lock lock;
	static T* object; 
protected:
	Singleton() { }; 
public:
	static T * instance(); 
};
Lock Singleton::lock;

T * Singleton::Instance() {
// if object is not initialized, acquire lock 
	if (object == 0) {
		lock.AcquireLock();
// If two threads simultaneously check and pass the first "if"
// condition, then only the one who acquired the lock first
// should create the instance 
		if (object == 0) {
			object = new T; 
		}
		lock.ReleaseLock(); 
	}
	return object; 
}

int main() {
// foo is any class defined for which we want singleton access 
	Foo* singleton_foo = Singleton<Foo>::Instance();
	return 0;
}

The general method to make a program thread safe is to lock shared resources whenever write permission is given This way, if one thread is modifying the resource, other threads can not modify it.