2016-01-18 19:18:06 -08:00
|
|
|
//
|
|
|
|
|
// Semaphore.swift
|
|
|
|
|
// XIONControlPanel
|
|
|
|
|
//
|
|
|
|
|
// Created by Charles Magahern on 1/18/16.
|
|
|
|
|
// Copyright © 2016 XION. All rights reserved.
|
|
|
|
|
//
|
|
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
2016-07-24 00:14:04 -07:00
|
|
|
class Semaphore
|
|
|
|
|
{
|
2017-05-13 00:40:03 -07:00
|
|
|
fileprivate var _semaphore: DispatchSemaphore
|
2016-01-18 19:18:06 -08:00
|
|
|
|
|
|
|
|
init(value: Int)
|
|
|
|
|
{
|
2017-05-13 00:40:03 -07:00
|
|
|
_semaphore = DispatchSemaphore(value: value)
|
2016-01-18 19:18:06 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func wait()
|
|
|
|
|
{
|
|
|
|
|
self.wait(nil)
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-13 00:40:03 -07:00
|
|
|
func wait(_ untilDate: Date?)
|
2016-01-18 19:18:06 -08:00
|
|
|
{
|
2017-05-13 00:40:03 -07:00
|
|
|
var time: DispatchTime = DispatchTime.distantFuture
|
|
|
|
|
if let untilDate = untilDate {
|
|
|
|
|
time = .now() + .milliseconds(Int(untilDate.timeIntervalSinceNow * 1000))
|
2016-01-18 19:18:06 -08:00
|
|
|
}
|
|
|
|
|
|
2017-05-13 00:40:03 -07:00
|
|
|
let result = _semaphore.wait(timeout: time)
|
|
|
|
|
if (result != .success) {
|
|
|
|
|
print("semaphore timed out")
|
|
|
|
|
}
|
2016-01-18 19:18:06 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func signal()
|
|
|
|
|
{
|
2017-05-13 00:40:03 -07:00
|
|
|
_semaphore.signal()
|
2016-01-18 19:18:06 -08:00
|
|
|
}
|
|
|
|
|
}
|