Wednesday, February 8, 2012

线程之间怎么通讯?什么是critical section/semaphore/mutax,区别?

线程之间怎么通讯?什么是critical section/semaphore/mutax,区别?
网上找到这么一段话,

how do 2 threads communicate?

Basically via memory i.e. member fields of a class. Any thread can write into a single field and let any other thread read its value.
But if you need to make sure that any value written into the field will also be found/read by another thread, you need to put the statements accessing your communication field into blocks

synchronized( lockObj ){ commField= ...; }

The lockObj is a central object (also called semaphore or mutex - for mutual exclusion ) you should choose carefully so that it can be accessed from all your classes and very early: think of an instance of java.lang.Class : that's a foolproof singleton.

I want to discourage you from using the "fast and easy" synchronized qualifier for methods. This way you end up with a mess of Locks and creating deadlocks!

what is critical section

In concurrent programming a critical section is a piece of code that accesses a shared resource (data structure or device) that must not be concurrently accessed by more than one thread of execution. A critical section will usually terminate in fixed time, and a thread, task or process will have to wait a fixed time to enter it (aka bounded waiting). Some synchronization mechanism is required at the entry and exit of the critical section to ensure exclusive use.

--
what is semaphore

In computer science, a semaphore is a variable or abstract data type that provides a simple but useful abstraction for controlling access by multiple processes to a common resource in a parallel programming environment.

--
A mutex is essentially the same thing as a binary semaphore, and sometimes uses the same basic implementation. However, the term "mutex" is used to describe a construct which prevents two processes from executing the same piece of code, or accessing the same data, at the same time. The term "binary semaphore" is used to describe a construct which limits access to a single resource.

In many cases a mutex has a concept of an "owner": the process which locked the mutex is the only process allowed to unlock it. In contrast, semaphores generally do not have this restriction, something the producer-consumer example above depends upon.

No comments:

Post a Comment