Multi-thread programming

Threads 
and 
processes:

Multiple 
threads
 in
 a
 single
 process 
have 
access 
to
 the
 same 
memory.

 By
 contrast,
 multiple 
processes 
have
 separate 
regions 
of
 memory
 and
 can
only 
communicate
 by
 special
 mechanisms.

The
 processor 
load s
and 
saves
 a
 separate
 set 
of 
registers 
for
 each 
thread.

Remember,
 each 
process 
has 
one 
or 
more 
threads,
 and
 the
 processor 
switches
 between
 threads.

Mutexes 
and
 semaphores:


Synchronized 
methods
 (in 
Java):

Each
 object 
in 
Java 
has 
its 
own 
mutex.

Whenever
 a 
synchronized
 method
 is 
called,
 the
 mutex
 is
 locked.
Deadlock:

Thread
1:


acquire(lock1);

acquire(lock2);

[do
stuff]

release(lock1);

release(lock2);


Thread
2:


acquire(lock2);

acquire(lock1);

[do
stuff]

release(lock2);

release(lock1);

Suppose 
that
 thread
1 
is 
executed
 to 
just
 after 
the 
first 
statement.

Then,
the
 processor 
switches 
to 
thread
2 
and
 executes 
both 
statements.

 Then,
the 
processor 
switches 
back
 to 
thread
1 
and 
executes 
the
 second 
statement. 

In 
this 
situation, 
thread
1
 will
 be
 waiting 
for 
thread
2
 to
release 
lock1, 
and
 thread
2 
will
 be 
waiting
 for
 thread
1 
to
 release 
lock2. 

Both 
threads 
will 
be 
stuck 
indefinitely.

Preventing
 Deadlock
:
we 
can 
prevent 
deadlock
 if
 we 
assign
 an
 order
 to 
our 
locks 
and 
require
 that
 locks 
always 
be 
acquired 
in
order.
For 
example,
if 
a 
thread 
needs
 to 
acquire 
locks
 1,
 5,
and
 2,
it
 must 
acquire 
lock
1,
 followed 
by 
lock
2, 
followed
 by 
lock
5.

 That 
way 
we
 prevent
 one
thread
 trying 
to
 acquire 
lock
1 
then 
lock
2,
 and
 another 
thread 
trying 
to 
acquire
 lock
2 
then 
lock
1,
 which 
could
 cause 
deadlock.

 (Note
 that 
this
approach
 is
 not 
used
 very 
often 
in
 practice.)


Reference from:
Hacking a Google interview (From MIT)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s