簡體   English   中英

這種同步算法如何工作?

[英]How does this synchronization algorithm work?

do { while (test_and_set(&lock))
; /* do nothing */
/* critical section */
lock = false;
/* remainder section */
} while (true);



boolean test_and_set (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}

我不明白它應該如何工作,因為無論while(test_and_set(&lock)返回什么,無論是true還是false,do {}代碼仍會運行臨界區。它什么都不做,然后立即運行關鍵部分,那么這有助於同步線程?

不管test_and_set返回什么test_and_set 請注意, test_and_set返回給定的位置的先前值,因此while(test_and_set(&lock)); (注意終止分號!)將在CPU上旋轉,而另一個線程“擁有”鎖。

但請注意, test_and_set的實際實現不是原子的,因此實際上並不是線程安全的。

如果我將代碼重新格式化為這樣,也許會有所幫助?

do {
    while (test_and_set(&lock)) {
        /* do nothing */
    }
    /* critical section */
    lock = false;
    /* remainder section */
} while (true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM