PThreads in Swift

Here’s some code that implements pthreads via swift.

class PTTask {
	init () {
	}
	func run() -> Int32 {
		let threadPtr = UnsafeMutablePointer.alloc(1)
		let selfPtr = UnsafeMutablePointer.alloc(1)
		selfPtr.memory = self
		let attrPtr = UnsafeMutablePointer.alloc(1)
		
		var err = pthread_attr_init(attrPtr)
		guard err == 0 else { return err }
		err = pthread_attr_setdetachstate(attrPtr, PTHREAD_CREATE_DETACHED);
		guard err == 0 else {
			pthread_attr_destroy(attrPtr)
			return err
		}
		err = pthread_create(threadPtr, attrPtr, { (p: UnsafeMutablePointer) ->
													UnsafeMutablePointer in
			let mePtr = unsafeBitCast(p, UnsafeMutablePointer.self)
			let me = mePtr.memory
			
			for _ in 1 ... 5 {
				print("\(me.hello)")
			}
				return nil
			},
			selfPtr)
		
		pthread_attr_destroy(attrPtr)
		sleep(5)	// give thread time to finish
		return err
	}

	let hello = "Hello World"
}

There are some memory leaks up there, FYI…

Leave a Reply

Your email address will not be published. Required fields are marked *