iOS原理之CGD-dispatch_once的底层实现

//
//  GCD-DispatchOnce-ViewController.swift
//  iOS底层
//
//  Created by yanqunchao on 2019/5/21.
//  Copyright © 2019 yanqunchao. All rights reserved.
//

import UIKit



class GCD_DispatchOnce_ViewController: UIViewController {

    var onceToken :Int = 0
    
    typealias dispatchBlockT = (()->())
    typealias dispatchBlockInvoke = ((dispatchBlockT)->())
    
    let semaphore =  DispatchSemaphore(value: 1)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        
        for _ in 0..<4 {
            DispatchQueue.global().async {
                self._dispatchOnce(predicate: &self.onceToken) {
                    print("-------创建单利")
                }
            }
        }
        print(semaphore)
    }
 
    func _dispatchOnce(predicate:UnsafeMutablePointer?,block:dispatchBlockT) {
        print("进入函数------")
        semaphore.wait()
        print("锁住线程-------\(Thread.current)")
        if  predicate!.pointee != -1 {
            dispatch_once_f(predicate: predicate, ctxt: block, invokeFunc: _dispatch_Block_invoke)
        } else {
            print("开启线程-------\(Thread.current)")
            semaphore.signal()
        }
    }
    
    
    func dispatch_once_f(predicate:UnsafeMutablePointer?,ctxt:dispatchBlockT,invokeFunc:@escaping dispatchBlockInvoke) {
        invokeFunc(ctxt)
        predicate!.pointee = -1
        print("开启线程-------\(Thread.current)")
        semaphore.signal()
    }
    
    func _dispatch_Block_invoke(block:dispatchBlockT) {
        block()
    } 
}

你可能感兴趣的:(iOS原理之CGD-dispatch_once的底层实现)