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<Int>?,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<Int>?,ctxt:dispatchBlockT,invokeFunc:@escaping dispatchBlockInvoke) {
        invokeFunc(ctxt)
        predicate!.pointee = -1
        print("开启线程-------\(Thread.current)")
        semaphore.signal()
    }
    
    func _dispatch_Block_invoke(block:dispatchBlockT) {
        block()
    } 
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容