[swift-users] Swift and Threads

Gerriet M. Denkmann gerriet at mdenkmann.de
Mon Sep 12 23:03:27 CDT 2016


This function works flawlessly in Release build:

func markAndTell( talk: Bool, number: Int)
{
	let nbrOfThreads = 8
	let step = 2
	let itemsPerThread = number * step
	let bitLimit = nbrOfThreads * itemsPerThread
	var bitfield = [Bool](count: bitLimit, repeatedValue: false)

	let queue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 );
	dispatch_apply( Int(nbrOfThreads), queue,
		{ ( idx: size_t) -> Void in
			
			let startIndex = itemsPerThread * Int(idx)
			let endIndex = min( startIndex + itemsPerThread, bitLimit )
			if talk { print("Thread[\(idx)] does \(startIndex) ..< \(endIndex)")}
			
			var currIndex = startIndex
			while( currIndex < endIndex )
			{
				bitfield[currIndex] = true	//	this might crash
				currIndex += step
			}
		}
	)
}

But it does not work in Debug builds.

“does not work” means: for !talk and any number > 0 or: talk and number ≥ 110:

malloc: *** error for object 0x101007808: incorrect checksum for freed object 
- object was probably modified after being freed. *** set a breakpoint in malloc_error_break to debug

Or:
fatal error: UnsafeMutablePointer.initializeFrom non-following overlapping range

Or:
just plain wrong data in bitfield.

So: is the code ok and the compiler broken in Debug mode?
Or is the code fundamentally wrong and that it works in Release is just a fluke?
If so: how could it be fixed?

Btw.: no problems with bitfield malloced into some UnsafeMutablePointer<UInt8>.

Gerriet.


More information about the swift-users mailing list