LoginSignup
2
2

More than 5 years have passed since last update.

Boolによる簡易排他制御

Last updated at Posted at 2017-09-16

連続して同じ処理が走らないようにBoolを使った排他制御をすることがあると思います。そういったケースで使えるプチ便利なクラスを書きました。

class BooleanLock {

    private var doing = false

    func withLock(_ f: (@escaping () -> Void) -> Void) {
        if doing { return }

        doing = true
        f(unlock)
    }

    private func unlock() {
        doing = false
    }
}

使い方

class BooleanLockTest {

    ...

    private let fetching = BooleanLock()

    ...

    func doFetch() {
        fetching.withLock { unlock in
            // do something
            // ...

            unlock()
        }
    }    
}

以上

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2