• GCD 实现生产-消费 模式


    #import "ViewController.h"
    
    @interface ViewController (){
        
    }
    @property (nonatomic,strong)    dispatch_semaphore_t sema;
    
    @end
    
    @implementation ViewController
    
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
         _sema = dispatch_semaphore_create(1);
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_queue_create("custom_dis", 0);
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            
            if (![[NSThread currentThread]  isMainThread]) {
                NSLog(@"===异步线程===============");
            }
            
             for (int i = 0; i<10; i++) {
                 
                 dispatch_semaphore_wait(_sema, DISPATCH_TIME_FOREVER);
                 
                 dispatch_group_async(group, queue, ^{
                     if (![[NSThread currentThread]  isMainThread]) {
                         NSLog(@"===异步线程===============");
                     }
                     
                     [self doCustomSomting];
                     
                     
                 });
                 
                 
             }
             
    
         });
        
    
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    }
    
    -(void)doCustomSomting{
        
        sleep(2);
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (![[NSThread currentThread]  isMainThread]) {
                NSLog(@"===异步线程===============");
            }
            sleep(1);
    
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if ([[NSThread currentThread]  isMainThread]) {
                    NSLog(@"===主线程===============");
                }
                NSLog(@"=====compeletSomting=========");
                
                dispatch_semaphore_signal(_sema);
    
            });
            
            
            
        });
        
        
        
        
    }
    
    
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
  • 相关阅读:
    Python lambda 多变量
    Python 的 zip 和 dict 组合 生成新字典
    Solr集群Replication配置与实践(四)
    linux系统搭建zookeeper集群(二)
    linux系统中安装solr搜索引擎(一)
    Solr搜索引擎集群搭建(三)
    CentOS7的yum重装
    安装konga 路由设置
    安装Snipe-IT资产管理系统
    安装GLPI资产管理
  • 原文地址:https://www.cnblogs.com/DamonTang/p/4029396.html
Copyright © 2020-2023  润新知