Help us understand the problem. What is going on with this article?

Swiftでのthread-safeなデータ操作

More than 3 years have passed since last update.

atomic

最近Swiftでもっぱら書くことが多くなり
AtomicReference的なライブラリが欲しく作成してみました。

Lock.swift
class locker {
    private var l = NSRecursiveLock()

    func lock() -> Bool {
        self.l.lock()
        return true
    }

    func unlock() {
        self.l.unlock()
    }

    func safeCall<R>(f: () -> R) -> R {
        var r: R
        self.lock()
        r = f()
        self.unlock()
        return r
    }
}

Atomic.swift
// lockerを継承して、safeCallで安全に値を扱う。
class AtomicValue <T> : locker {
    private var value: T?

    init(v: T?) {
        self.value = v
    }

    func setV(v: T?) {
        self.safeCall(
            {() in
                self.value = v
            }
        )
    }

    func setV(f: (T?) -> T?) {
        self.safeCall(
            {() in
                self.value = f(self.value)
            }
        )
    }

    func getV() -> T? {
        return self.safeCall(
            {() -> T? in
                return self.value
            }
        )
    }

    func getV_and_SetV(v: T?) -> T? {
        return self.safeCall(
            {() -> T? in
                let r = self.value
                self.value = v
                return r
            }
        )
    }
}

使い方

Sample.swift
private var value = AtomicValue <Int> (v: 0)
private var counter: Int {
    get {
        return value.getV()!
    }

    set {
        value.setV(
            {(v: Int?) -> Int? in
                if let vv = v {
                    return vv + 1
                }
                return 0
            }
        )
    }
}

safeCallの中でlockをすると、dead lockになってしまうので
NSRecursiveLockを使っています。

しかし、Swiftは中々慣れない(。。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away