[swift-users] Counting in Threads

Gerriet M. Denkmann g at mdenkmann.de
Wed Oct 12 02:47:23 CDT 2016


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.



More information about the swift-users mailing list