Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

4. Thread Synchronization > Mutexes - Pg. 92

The problem, in both examples, is a race condition. Race conditions are errors caused by a sequence of events. In the first example, both threads check race_list simultaneously, discover that it is empty, and assign 0 as the unit number. In the second example, MOD_QUIESCE returns error-free, a race_softc structure is then added to race_list , and finally MOD_UNLOAD completes. NOTE One characteristic of race conditions is that they're hard to reproduce. Ergo, the results were doctored in the preceding examples. That is, I caused the threads to context switch at specific points to achieve the desired outcome. Under normal conditions, it would have taken literally millions of attempts before those race conditions would occur, and I didn't want to spend that much time. Preventing Race Conditions Race conditions are prevented using locks. Locks, also known as synchroniza- tion primitives, are used to serialize the execution of two or more threads. For example, the race conditions in Listing 4-1, which are caused by concurrent access to race_list , can be prevented by using a lock to serialize access to race_list . Before a thread can access race_list , it must first acquire the foo lock. Only one thread can hold foo at a time. If a thread cannot acquire foo , it cannot access race_list and must wait for the current owner to relinquish foo . This protocol guarantees that at any moment in time only one thread can access race_list , which eliminates Listing 4-1's race conditions. There are several different types of locks in FreeBSD, each having its own characteristics (for example, some locks can be held by more than one thread). The remainder of this chapter describes the different types of locks available in FreeBSD and how to use them. Mutexes Mutex locks (mutexes) ensure that at any moment in time, only one thread can access a shared object. Mutex is an amalgamation of mutual and exclusion. NOTE The foo lock described in the previous section was a mutex lock. FreeBSD provides two types of mutex locks: spin mutexes and sleep mutexes. Spin Mutexes Spin mutexes are simple spin locks. If a thread attempts to acquire a spin lock that is being held by another thread, it will "spin" and wait for the lock to be released. Spin, in this case, means to loop infinitely on the CPU. This spin- ning can result in deadlock if a thread that is holding a spin lock is interrupted or if it context switches, and all subsequent threads attempt to acquire that lock. Consequently, while holding a spin mutex all interrupts are blocked on the local processor and a context switch cannot be performed. T h r e a d S y n c h ro n i z a t i on 65