为什么需要额外的`CMP`命令来实现测试和设置(TSL)?

时间:2014-01-09 15:00:12

标签: multithreading assembly operating-system thread-safety locking

以下代码来自维基百科(http://en.wikipedia.org/wiki/Test-and-set

enter_region:        ; A "jump to" tag; function entry point.

  tsl reg, flag      ; Test and Set Lock; flag is the
                     ; shared variable; it is copied
                     ; into the register reg and flag
                     ; then atomically set to 1.

  cmp reg, #0        ; Was flag zero on entry_region?

  jnz enter_region   ; Jump to enter_region if
                     ; reg is non-zero; i.e.,
                     ; flag was non-zero on entry.

  ret                ; Exit; i.e., flag was zero on
                     ; entry. If we get here, tsl
                     ; will have set it non-zero; thus,
                     ; we have claimed the resource as-
                     ; sociated with flag.

leave_region:
  move flag, #0      ;store 0 in flag
  ret                ;return to caller

据我所知,这两个命令tsl reg, flagcmp reg, #0可以合并为一个命令tsl reg, flag,它共同完成三件事:(1)将flag复制到{{} 1}}(2)将reg设置为flag(3)测试1是否为零。从reg命令中分离(3)有什么好处或必要性?有没有人有这方面的想法?

1 个答案:

答案 0 :(得分:0)

tsl实际上并没有测试flag的内容(除了它的名字);它只是原子地将flag复制到reg。在x86中,它通常使用xchg或比较和交换指令实现,当后者可用时。