Create pthread using Swift

To opt out of QOS, I'm attempting to create a pthread using Swift objects (to take advantage of closures). The issue is calling the Swift function in the pthread causes (at times) a segmentation fault (assuming it's dealing with referencing self).

The code below occasionally crashes in Release builds, during runtime.

private var context = UnsafeMutablePointer<() -> Void>.allocate(capacity: 1)
self.context.initialize(to: {})

self.context.pointee = { [weak self] in
    self?.main()
}

try throwError(pthread_create(&self.threadId, &attr, { ctx in
    pthread_setname_np("custom.thread")
    ctx.load(as: (() -> Void).self)()
    return nil
}, self.context))

I've also tried the following, which occasionally crashes in Debug and Release on the line self.context.pointee = self:

private var context = UnsafeMutablePointer<CustomThread>.allocate(capacity: 1)
self.context.pointee = self

try throwError(pthread_create(&self.threadId, &attr, { ctx in
    pthread_setname_np("custom.thread")
    ctx.load(as: CustomThread.self).main()
    return nil
}, self.context))

Any suggestions/help would be appreciated as to resolving the segmentation fault.

Create pthread using Swift
 
 
Q