ios 异步线程 NSLock 小结

本文探讨了在Swift中如何创建并管理线程,并通过使用锁来确保线程间的同步执行,防止数据竞争,展示了不同场景下线程的运行状态及锁的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

oc
1

    dispatch_queue_t q =dispatch_queue_create("thread-one",DISPATCH_QUEUE_SERIAL) ;
    dispatch_async(q, ^{
     //to  do
    });
     // 获取 名字的方法 
    // NSLog(@"%s", dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL));

2

   NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(display) object:nil];
    thread.name = @"thread-three";
    [thread start];

swfit
1

     let queue1 = DispatchQueue(label: "thread-one")
        queue1.async {
        // to do ;
        }

2

      let thread1 = Thread(target: self, selector: #selector(ViewController.display), object: nil)
        thread1.name = "thread1"
        thread1.start()

Nslock使用

 let thread1 = Thread(target: self, selector: #selector(ViewController.display), object: nil)
        thread1.name = "thread1"
        thread1.start()
        let thread2 = Thread(target: self, selector: #selector(ViewController.display), object: nil)
        thread2.name = "thread2"
        thread2.start()
        let thread3 = Thread(target: self, selector: #selector(ViewController.display), object: nil)
        thread3.name = "thread3"
        thread3.start()
    func display(){

       // lock.lock() //打开
            //耗时操作
            self.name =  Thread.current.name! ;
            //
            Thread.sleep(forTimeInterval: TimeInterval(5))

                    print("\(self.name) -- \(Thread.current.name!) ")
       // lock.unlock()//打开

    }

输出

thread2 -- thread3 
thread2 -- thread1 
thread2 -- thread2 

混乱了,修改display方法 注释打开 输出

thread3 -- thread3 
thread1 -- thread1 
thread2 -- thread2 

正常了

   func display(){
       lock.lock()
            self.name =  Thread.current.name!
        let timer:Timer = Timer(timeInterval: 5.0,
                                target: self,
                                selector: #selector(ViewController.log),
                                userInfo: nil,
                                repeats: false)

        // 将定时器添加到运行循环
        RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
        RunLoop.current.run()
       lock.unlock()

    }
    func log(){

      print("\(self.name) -- \(Thread.current.name!) ")
        Thread.sleep(forTimeInterval: 10);
    }

如果 lock 的内容 有异步执行的 会等异步执行完 再解锁 上面 一共过了 15s 才解锁

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值