Thread::Semaphore - 執行緒安全信號量
本文檔說明 Thread::Semaphore 版本 2.13
use Thread::Semaphore;
my $s = Thread::Semaphore->new();
$s->down(); # Also known as the semaphore P operation.
# The guarded section is here
$s->up(); # Also known as the semaphore V operation.
# Decrement the semaphore only if it would immediately succeed.
if ($s->down_nb()) {
# The guarded section is here
$s->up();
}
# Forcefully decrement the semaphore even if its count goes below 0.
$s->down_force();
# The default value for semaphore operations is 1
my $s = Thread::Semaphore->new($initial_value);
$s->down($down_value);
$s->up($up_value);
if ($s->down_nb($down_value)) {
...
$s->up($up_value);
}
$s->down_force($down_value);
信號量提供一種機制來規範資源存取。與鎖定不同,信號量不會繫結到特定純量,因此可用於控制存取任何您想用它們控制的項目。
信號量不會將其值限制為 0 和 1,因此可用於控制可能有多個資源(例如檔案句柄)的存取。遞增和遞減的數量也不會固定為 1,因此執行緒可以一次保留或傳回多個資源。
new
建立一個新的 semaphore,並將其計數初始化為指定數字(必須為整數)。如果未指定數字,semaphore 的計數預設為 1。
down
方法會將 semaphore 的計數減少指定的數字(必須為整數 >= 1),或減少 1(如果未指定數字)。
如果 semaphore 的計數會降至低於零,此方法會封鎖,直到 semaphore 的計數大於或等於您要減少 semaphore 計數的數量。
這是 semaphore 的「P 運算」(名稱源自荷蘭語「pak」,意為「擷取」-- semaphore 運算由已故的荷蘭人 Dijkstra 命名)。
down_nb
方法嘗試將 semaphore 的計數減少指定的數字(必須為整數 >= 1),或減少 1(如果未指定數字)。
如果 semaphore 的計數會降至低於零,此方法會傳回 false,且 semaphore 的計數維持不變。否則,semaphore 的計數會遞減,且此方法會傳回 true。
down_force
方法會將 semaphore 的計數減少指定的數字(必須為整數 >= 1),或減少 1(如果未指定數字)。此方法不會封鎖,且可能會導致 semaphore 的計數降至低於零。
down_timed
方法嘗試在指定的逾時期間(以秒為單位,必須為整數 >= 0)內將 semaphore 的計數減少 1 或減少指定的數字。
如果 semaphore 的計數會降至低於零,此方法會封鎖,直到 semaphore 的計數大於或等於您要減少 semaphore 計數的數量,或直到逾時為止。
如果逾時,此方法會傳回 false,且 semaphore 的計數維持不變。否則,semaphore 的計數會遞減,且此方法會傳回 true。
up
方法會將 semaphore 的計數增加指定的數字(必須為大於或等於 1 的整數),或在未指定數字時增加 1。
如果 up
將 semaphore 的計數增加到高於 down
嘗試遞減的數量,這將解除任何嘗試 down
semaphore 而遭到封鎖的執行緒。例如,如果有三個執行緒遭到封鎖,嘗試將 semaphore 遞減 1,而另一個執行緒將 semaphore 增加 2,則兩個遭到封鎖的執行緒(哪兩個不確定)將會解除封鎖。
這是 semaphore 的「V 運算」(名稱源自荷蘭語「vrij」,意為「釋放」)。
由 Thread::Semaphore 建立的 semaphore 可以用於具執行緒和非執行緒的應用程式中。這讓您可以撰寫可能使用 semaphore 的模組和套件,且可以在任一環境中運作。
MetaCPAN 上的 Thread::Semaphore:https://metacpan.org/release/Thread-Semaphore
CPAN 發行套件的程式碼存放庫:https://github.com/Dual-Life/Thread-Semaphore
此發行套件的 examples 目錄中的範例程式碼在 CPAN 上。
Jerry D. Hedden,<jdhedden AT cpan DOT org>
此程式為自由軟體;您可以在與 Perl 相同的條款下重新發行或修改它。