iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
0
class Book {
    let author:String;
    let title:String;
    let stockNumber:Int;
    var reader:String?
    var checkoutCount = 0;
    
    init(author:String, title:String, stock:Int) {
        self.author = author;
        self.title = title;
        self.stockNumber = stock;
    }
}
import Foundation

class Pool<T> {
    private var data = [T]();
    private let arrayQ = dispatch_queue_create("arrayQ", DISPATCH_QUEUE_SERIAL);
    private let semaphore:dispatch_semaphore_t;
    
    init(items:[T]) {
        data.reserveCapacity(data.count);
        for item in items {
            data.append(item);
        }
        semaphore = dispatch_semaphore_create(items.count);
    }
    
    func getFromPool() -> T? {
        var result:T?;
        if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) == 0) {
            dispatch_sync(arrayQ, {() in
                result = self.data.removeAtIndex(0);
            })
        }
        return result;
    }
    
    func returnToPool(item:T) {
        dispatch_async(arrayQ, {() in
            self.data.append(item);
            dispatch_semaphore_signal(self.semaphore);
        });
    }
}

上一篇
Day9: Chapter6: Singleton 模式(上)
下一篇
Day11:
系列文
Pro Design Patterns in Swift517
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言