Saturday, February 20, 2010

Exceptional exception handling in C++

#include

using namespace std;

//Global
int a = 20;

void foo()
try {
throw a;
}
catch(int &x)
{
// You can't modify value of "a"
x = 10;
}

int main()
{
foo();
cout<<"A="< }

A=20 !!!!
When you write "throw a", an invisible, phantom exception object gets created. You pass reference to that object and hence any change made to original object have no effect.

Friday, February 19, 2010

Mutex v/s Semaphore v/s Spinlock

Similarity

- All are used for synchronization

Difference

Mutex provides one person to access a resource at a time, others must wait in a queue. Once person is done, the guy next in the queue acquire the resource.
So access is serial, one guy after other.

Semaphore provides more than one(up to N) guys to access N resources. So it gives you parallel access to a resource.

Spinlock is an aggressive mutex. In mutex, if you find that resource is locked by someone else, you (the thread/process) switch the context and start to wait(non-blocking).
Whereas spinlocks do not switch context and as soon as resource is free, they go and grab it. In this process of spinning, they consume many CPU cycles. Also, on a uni-processor machine they are useless and perform very badly (do I need to explain that?).

Thursday, February 4, 2010

GL: Question

- fun(int, int);
fun(char, char)
Are they overloaded properly?

- Using static variable in a member function?

- Finding the common node of two link lists?

- Implement BFS, DFS?

- Inorder, preorder is DFS or BFS?

- What is a heap?

- Deleting a node in BST?

- Difference of memcpy() and strcpy()