多线程编程

来源:互联网 发布:鲁豫 知乎 编辑:程序博客网 时间:2024/06/04 01:27

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)

0 0
原创粉丝点击