Search code examples
swiftgrand-central-dispatch

why dispatchqueue.global() still alive after deinit


deinit {
    print("deinit")
}

DispatchQueue.global().async { [weak self] in
            
    while(true){
        print(self)
        print("sleep")
        sleep(1)
    }
}

Although deinit in class is called, infinite loop in DispatchQueue.global() is still alive.

In that case, for example,

Optional(<OutOfKiosk.DialogFlowPopUpController: 0x150116e00>)

sleep

Optional(<OutOfKiosk.DialogFlowPopUpController: 0x150116e00>)

sleep

deinit (after deinit)

nil

sleep

nil

sleep

...(repeat)


I will really appreciate it if someone teach me why

Solution

  • DispatchQueue.global() returns the global system queue. https://developer.apple.com/documentation/dispatch/dispatchqueue/2300077-global

    GCD manages a shared thread pool, decides and adds blocks of code to global dispatch queue to execute it.

    In Debug Memory Graph, You can figure out many dispatch queues alive enter image description here

    your execution executed on dispatch queue is not related to DialogFlowPopUpController instance's deinit

    // your execution should not be completed because there are no break statement
    { [weak self] in
        while(true){
            print(self)
            print("sleep")
            sleep(1)
        }
    }
    

    How about change your execution to break infinity loop

    DispatchQueue.global().async { [weak self] in
        while(self != nil){
            print(self)
            print("sleep")
            sleep(1)
        }
    }