Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

semaphore_wait_trap when accessing class singleton using Swift

I'm running into a strange problem. I can access my classes singleton instance just fine, but if I try to access it again it just appears to hang. Here is a simple version of the code:

private let _SharedInstance = MyManager()

class MyManager: NSObject {

    class var sharedInstance: MyManager {
        return _SharedInstance
    }

    override init() {
        super.init()

        println("init")

        println(self.accessToken())
        println(MyManager)
        println("test 1")
        println(MyManager.sharedInstance)
        println("test 2")
    }

}

In this case it is calling it from within the init of itself, but it happens elsewhere.

The code never gets to test 2. As soon as it access MyManager.sharedInstance it hangs. No errors or warnings.

If I pause the debugger I can see it is currently having on semaphore_wait_trap

Picture (difference class names):

Stack trace

Restarting Xcode or the computer hasn't helped.

like image 256
rdougan Avatar asked Feb 11 '23 12:02

rdougan


1 Answers

When MyManager gets created, a lock is used to prevent other threads from accessing the variable while it is being created. You cannot access this variable from within the init method. It doesn't just seem to hang your program, it will every single time hang your program because you are creating a deadlock.

Solution: Don't use that variable from your init method. Don't access _SharedInstance from your init method, directly or indirectly.

like image 128
gnasher729 Avatar answered Feb 14 '23 08:02

gnasher729