问题
There's an example in Maurice Bach's The Design of the Unix Operating System that mentions how it's possible for a doubly linked list to be destroyed due to a context switch during its creation. (He goes on to say that this is prevented by raising the processor level during such critical regions of code, but I'm having trouble understanding his reasoning that tries to show the problem in the first place) The sample code that he includes is as follows:
struct queue {
} *bp, *bp1;
bp1 -> forp = bp -> forp;
bp1 -> backp = bp;
bp -> forp = bp1;
/* consider possible context switch here */
bp1 -> forp -> backp = bp1;
the diagram he writes shows initially:
| |
| bp1 |
-> | | -> | |
<- | bp | <- | |
then, to show the final state:
-> | | -> | | -> | |
<- | bp | <- | bp1 | | |
^
\ /
-----------------------
I'm trying to walk through the logic, but i can't tell why the code would lead to a broken doubly linked list as shown. Can someone explain what's occuring during the context switch to cause this problem?
(p.s. would have tagged as doubly-linked-list, but no tag creation permissions)
回答1:
My mistake in not reading carefully enough - Maurice says in the page before the diagrams how the context switch would break the code IF another process "were to manipulate the pointers on the linked list before the original process ran again." I was confused because I was trying to get enough information from just the diagram and the code, neither of which mentioned the fact that the process being switched to would be handling the same data structure in memory (despite there having been a context switch.. still not a 100% clear/motivated example imho). Either way, apparently my own kernel had a bit of data corruption when i made the context switch from reading one page to the next..
来源:https://stackoverflow.com/questions/6060456/context-switch-during-doubly-linked-list-creation