Tokens Vs. Mutexes
Tokens are similar to mutexes in that they can, if used correctly, prevent multiple threads from accessing a shared resource at the same time. Unlike mutexes, however, they do NOT exclude other threads from accessing the resource while they are blocked or asleep. In general terms, they're both locks: your thread gets a lock (which prevents other threads from having it), does some work, and then releases it for another thread to use.
It's important here to recall how threads interact with each other when sharing resources. There are a number of ways that a thread can be stopped and another thread to be started:
- Timeslicing: the scheduler tries to ensure that all threads get a fair chance to run, so it runs each thread for a brief period of time (a timeslice) and then switches to another thread.
- Concurrent Execution: In multiprocessor computers, your thread may also be run at exactly the same time as another thread on a different CPU.
- Preemption: A thread may be preempted by a higher priority thread, such as a hardware interrupt or LWKT.
- Voluntary Blocking: A thread may voluntarily block (aka "go to sleep") if it has to wait for something, has no work to do, or calls a function that blocks-- note that even the call to acquire a lock can block.
Remember: the purpose of a lock is to keep other threads out while your thread is working on something. This table summarizes the situations in which tokens and mutexes work correctly to keep other threads "out".
Serializing Tokens | Mutexes | |
---|---|---|
Timeslicing | Works | Works |
Concurrent Execution | Works | Works |
Preemption | Works | Works |
Voluntary Blocking | FAILS | Works |
So what's the big deal? It seems like mutexes are the clear winner-- and in some cases it's important to be able to block and keep a lock. However, they also cause problems such as Deadlocks and Priority inversions. Dealing with these issues is very difficult and requires coordination at many different levels of the kernel:
“ | In fact, the fact that tokens do not deadlock coupled with the fact that there is no expectation of atomicity for earlier acquired tokens when later operations block leads to a great deal of code simplification. If you look at FreeBSD-5, you will notice that FreeBSD-5 passes held mutexes down the subroutine stack quite often, in order to allow some very deep procedural level to temporarily release a mutex in order to switch or block or deal with a deadlock. There is a great deal of code pollution in FreeBSD-5 because of this (where some procedures must be given knowledge of the mutexes held by other unrelated procedures in order to function properly). | ” |
—Matthew Dillon |
Read more about this topic: Serializing Tokens
Famous quotes containing the word tokens:
“It is the part of men to fear and tremble
When the most mighty gods by tokens send
Such dreadful heralds to astonish us.”
—William Shakespeare (15641616)