Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
14
Help us understand the problem. What is going on with this article?
@flowtumn

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

More than 5 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は中々慣れない(。。

14
Help us understand the problem. What is going on with this article?
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
flowtumn
safie
Safie(セーフィー)はクラウド録画カメラシェアNo.1!映像プラットフォームを開発・運営しています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
14
Help us understand the problem. What is going on with this article?