GCD,@synchronized 实现生产者-消费者模型

来源:互联网 发布:马自达 mx5 rf 知乎 编辑:程序博客网 时间:2024/06/06 09:16

//

//  ViewController.m

//  Test

//

//  Created by 小白 on 2016/12/10.

//  Copyright © 2016 LinJian. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()


@property (nonatomic,strong) NSMutableArray * arrM;


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.


    

    _arrM = [NSMutableArrayarray];

    

    [selfproducerFunc];

    [selfproducerFunc];

    [selfconsumerFunc];

    

    

}


- (void)producerFunc{

    

    dispatch_queue_t queue =dispatch_get_global_queue(0,0);

        

        dispatch_async(queue, ^{

            

            while (1) {

                

                if (_arrM.count ==10) {

                    

                    NSLog(@"库存已满,等待消费中");

                    

                }else{

                    

                    @synchronized (self) {

                        

                        NSLog(@"添加商品中");

                        

                        sleep(1);

                        

                        [_arrMaddObject:@"商品"];

                        

                        NSLog(@"添加完毕,当前商品数:%ld",_arrM.count);

                        

                    }

                    

                }

                

                sleep(5);

                

            }

            

        });

    

}


- (void)consumerFunc{

    

    dispatch_queue_t queue =dispatch_get_global_queue(0,0);

    

    dispatch_async(queue, ^{

        

        while (1) {

            

            if (_arrM.count ==0) {

                

                NSLog(@"库存已空,等待添加库存");

                

            }else{

                

                @synchronized (self) {

                    

                    NSLog(@"消耗商品中");

                    

                    sleep(1);

                    

                    [_arrMremoveObjectAtIndex:0];

                    

                    NSLog(@"商品消耗完毕,当前商品数:%ld",_arrM.count);

                    

                }

                

            }

            

            sleep(5);

        }

        

    });


}



- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



@end

0 0
原创粉丝点击