[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Threads
Brad Johnson wrote:
> BTW - What exactly is a semaphore? I've heard of them before, and I gather
> that they're similar to threads, but I know even less about them
A semaphore is an object whose purpose is best described as being
similar to that of the conch in "Lord of the Flies" or the notional
"patch pumpkin" in the Perl community. Possession of the conch means
that you have the right to talk. All others must remain silent.
Possession of the patch pumpkin means that you can patch the source tree
of the project you're working on, and all others must submit their
patches through you or wait until they get the pumpkin :)
Well, semaphores are kind of the same thing. When 2 processes want to
access a particular resource at the same time, a semaphore is used to
control who gets it. If one process grabs the semaphore, the other must
wait until it releases the semaphore before it can do anything with that
particular resource. Example: You have a block of shared memory or a
file shared between you and another process. You want to write to it but
there exists a danger that you will write over data that the other
process needs. You and the other process would agree to use one or more
semaphores to regulate access. When you want to write to your resource,
you take the semaphore. If the other process has taken the semaphore,
then it means you have to wait until they're done before doing the
write. When the other guy is reading, he also tries to take the
semaphore and if you're writing at that time, he's got to wait until
you're finished.
This is a simple use of semaphores but it illustrates the basic
concepts. They're really a bit more complicated; under SYSV IPC,
semaphores are actually access counters that limit the number of
processes that may do something at a particular time. It's akin to
having 2 or more patch pumpkins for the same resource, instead of just
the one, but the access restrictions are pretty much the same. It gets
kinda complicated, I know, but this is the basic method of inter-process
synchronization and access control in the Unix world. Some environments
may offer other options such as mutices and the things Windows and OS/2
call "critical sections" which are optimized for different scenarios
(e.g., different threads in the same process).
--
----------------------------------------------------------------------
Jeff Read <bitwize@geocities.com>
Unix Code Artist, Anime Fan, Really Cool Guy