[swift-users] Counting in Threads
Daniel Dunbar
daniel_dunbar at apple.com
Wed Oct 12 10:18:47 CDT 2016
I suspect one of the actual compiler people might tell me I shouldn't trust this, but in practice it works:
--
import Darwin.C
public class AtomicInt32 {
public fileprivate (set) var value : Int32 = 0
/// Create a new atomic integer with the specified initial value.
public init(_ value: Int32 = 0) {
self.value = value
}
/// Add one to the value.
public func increment () {
OSAtomicIncrement32(&value)
}
}
public func +=(int: AtomicInt32, value: Int32) {
OSAtomicAdd32(value, &int.value)
}
--
Would also love to know if compiler guarantees I *can* trust this.
Note that this has to be a class for this to be in any way safe, which means it is also rather inefficient if the use case was having a lot of them.
- Daniel
> On Oct 12, 2016, at 12:47 AM, Gerriet M. Denkmann via swift-users <swift-users at swift.org> wrote:
>
>
> How to translate this to Swift:
>
> __block atomic_uint_fast64_t counter = ATOMIC_VAR_INIT(0);
> dispatch_apply( nbrInterations, queue, ^void(size_t idx)
> {
> uint64_t tCount = 0;
> ... do some counting ...
> atomic_fetch_add_explicit( &counter, tCount, memory_order_relaxed );
> }
> )
>
> Currently I am using:
>
> var counter: UInt64 = 0
> let dsema = DispatchSemaphore(value: 1)
> DispatchQueue.concurrentPerform( iterations: nbrInterations )
> { ( idx: size_t) -> Void in
>
> var tCount: UInt64 = 0
> ... do some counting ...
> _ = dsema.wait(timeout: .distantFuture)
> counter += tCount;
> dsema.signal()
> }
>
> Is there a better way?
>
> Gerriet.
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
More information about the swift-users
mailing list