2/12/2014
2:18:00 PM 0

Semaphore

提供平行運算環境中,控制多個 thread 存取共享資源的一種策略模式,semaphore 是一個計數器的概念,用於保護共享的資源

譬如說有多個 thread 想要對同一塊記憶體變數進行讀寫時,在讀寫這塊記憶體之前,先獲得一個保護變數的 semaphore,當獲得這個 semaphore 時,其他人都不能對這塊記憶體進行讀寫,直到 semaphore 持有者釋放 semaphore 為止,在這種狀況下 semaphore 的值只有二進位的 0 或 1,稱為 binary semaphores,當受保護的資源數量大於 1 的任意數量時,稱作 counting semaphores,semaphore 常用於實作 publisher subscriber model & resource pool 中

Java Semaphore example
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TestSemaphore {
    public static void main(String[] args) {

        final int CONSUMER_COUNT = 20;
        final int RESOURCE_COUNT = 10;
        final ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(RESOURCE_COUNT);

        for (int i = 0; i < CONSUMER_COUNT; i++) {   
            final int INDEX = i;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        if (!semaphore.tryAcquire(2, TimeUnit.SECONDS))
                        {
                            throw new RuntimeException("timeout");
                        }

                        System.out.println("Acquire:" + INDEX + " / AvailablePermits:" + semaphore.availablePermits());

                        Thread.sleep(1000);
 
                        System.out.println("Release:" + INDEX + " / AvailablePermits:" + semaphore.availablePermits());
                        semaphore.release();
                   } 
                   catch (InterruptedException e) {
                   }
               }
           };

           exec.execute(run);
        }

        exec.shutdown();
    }
}

0 comments:

Post a Comment