Atomic<T>
类,适用于数字和字符串。dispatch
关键字。Chan<T>
,用于并发通信。Mutex
、Cond
、Once
、WaitGroup
Int
、Int8
、Int16
、Int32
、Int64
、UInt
、UInt8
、UInt16
、UInt32
、UInt64
、Float
、Double
、Bool
、String
==
, !=
, &&
, ||
, <=
, >=
, >
, <
, !
+
, -
, *
, /
, %
, <<
, >>
, ^
, &
, &+
, &-
, &*
, ++
, --
, +=
, -=
, *=
, /=
, %=
, +=
, <<=
, >>=
, ^=
, &=
var anum = IntA(100) // IntA is an alias for Atomic<Int>.
anum += 15 // Adds a value atomically.
let res = anum % 4 // Modulo operation atomically.
print("\(anum) \(res)") // prints '115 3'.
Safe 添加了一种简单的方法来分发进程。
dispatch {
print("Background")
}
print("Foreground")
一个新的 Chan<T>
类提供了一种简洁、简单的模型,用于并发共享对象。Chan<T>
的模式是基于 Go 通道。
let jobs = Chan<Int>(5) // buffered channel
let done = Chan<Bool>() // unbuffered channel
dispatch {
for ;; {
if let j = <-jobs {
print("received job \(j)")
} else {
print("received all jobs")
done <- true
return
}
}
}
for var j = 1; j <= 3; j++ {
jobs <- j
print("sent job \(j)")
}
jobs.close()
print("sent all jobs")
<-done
通道也可以迭代。
while let j = <-jobs {
print("received job \(j)")
}
print("received all jobs")
_select
关键字是一个多通道通信多路复用器,它作用于多个通道。_select
、_case
和_default
以下划线开头,以便它们不会与select
、case
和default
系统调用和关键字冲突。当_select
遇到具有数据的多个通道时,随机选择_case
let jobs1 = Chan<Int>()
let jobs2 = Chan<Int>()
dispatch {
for ;; {
_select {
_case(jobs1){ j in
print("received 1: \(j)")
}
_case(jobs2){ j in
print("received 2: \(j)")
}
}
}
}
for var j = 1; ; j++ {
jobs1 <- (j * 1000)
jobs2 <- (j * 2000)
NSThread.sleepForTimeInterval(1)
}
_select
可以包含一个单_default
,用于非阻塞操作。
_select {
_case(jobs1){ j in
print("received 1: \(j)")
}
_case(jobs2){ j in
print("received 2: \(j)")
}
_default {
print("channels not ready")
}
}
非常有用的同步 API。
let m = Mutex()
m.lock()
m.unlock()
m.lock {
// this block is locked
}
let c = Cond(Mutex())
c.wait() // wait for signal.
c.wait(0.25) // wait for signal or 250ms to pass.
c.signal() // signal to one wait.
c.broadcast() // signal to all waits.
func f(){
print("hey there")
}
let o = Once()
o.doit(f) // runs once
o.doit(f) // noop: cannot run twice
let dosomething : (NSTimeInterval, WaitGroup)->() = { (delay, wg) in
NSThread.sleepForTimeInterval(delay)
print("Function in background, duration: \(delay)")
wg.done()
}
let wg = WaitGroup()
wg.add(1)
dispatch { dosomething(0.40, wg) }
wg.add(1)
dispatch { dosomething(0.30, wg) }
wg.add(1)
dispatch { dosomething(0.15, wg) }
wg.add(1)
dispatch { dosomething(0.60, wg) }
wg.wait()
print("done")
将 Source/*.swift
文件复制到您的项目中。
手动安装时无需导入 import Safe
。
Josh Baker @tidwall
Safe 源代码在 MIT 许可证下可用。