你的位置:首页 > 操作系统

[操作系统]线程间通信和线程互斥


线程间通信

 1> 线程间通信分为两种

  • 主线程进入子线程(前面的方法都可以)

  • 子线程回到主线程

 2> 返回主线程

   NSLog(@"主线程:%@", [NSThread mainThread]);
NSString *urlStr = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1463455875&di=ef2da3f0fe711b471966aa1511483d0b&src=http://img4.duitang.com/uploads/item/201308/20/20130820094450_rsmYi.jpeg"; NSURL *url = [NSURL URLWithString:urlStr]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; self.imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // 返回主线程,刷新UI [self performSelectorOnMainThread:@selector(reloadImageView) withObject:nil waitUntilDone:YES];}- (void)reloadImageView{ // 进入主线程一般进行来安全判断 if ([NSThread isMainThread]) { // 刷新UI UIImage *showIamge = [UIImage imageWithData:self.imageData]; self.showImageView.image = showIamge; }}

点击触发事件,开辟子线程成功,在主线程中刷新UI,图片显示成功

  我们看看会发生什么问题

- (void)viewDidLoad {  [super viewDidLoad];  // 模拟买票系统  // 一共20张票,10个窗口卖  __block NSInteger count = 20;  dispatch_queue_t ticketQueue = dispatch_queue_create("sell ticket", DISPATCH_QUEUE_CONCURRENT);  for (int i = 0; i < 10; i ++) {    dispatch_async(ticketQueue, ^{      //这里相当于每个窗口卖2张票      for (int i = 0; i < 2; i ++) {        NSLog(@"买到了第%ld张票",count);        count--;      }    });  }}

运行的效果如下图,不同的售票窗口贩卖了同一张


  运行结果:


  以上两种方法小编进行了使用,以下两种方法大家有兴趣可以试试,小编就不进行使用了

  • 方法三 NSConditionLock 条件锁 可以设置条件

  官方文档解释:

   The NSConditionLock class defines objects whose locks can be associated with specific, user-defined conditions. Using an NSConditionLock object, you can ensure that a thread can acquire a lock only if a certain condition is met. Once it has acquired the lock and executed the critical section of code, the thread can relinquish the lock and set the associated condition to something new. The conditions themselves are arbitrary: you define them as needed for your application.

  个人理解:

   根据条件加锁与解锁。

  • 方法四 NSRecursiveLock 递归锁 多次调用不会阻塞已获取该锁的线程

  官方文档解释:

   NSRecursiveLock defines a lock that may be acquired multiple times by the same thread without causing a deadlock, a situation where a thread is permanently blocked waiting for itself to relinquish a lock. While the locking thread has one or more locks, all other threads are prevented from accessing the code protected by the lock.

  个人理解:

    同一个线程可以多次请求加锁,但不会引起死锁。